spring入门案例代码
时间: 2024-01-22 11:03:32 浏览: 30
对于Spring入门案例,有很多不同的示例代码。在这里,我提供一个简单的Spring MVC示例代码,用于展示如何使用Spring框架构建一个Web应用程序:
1. 首先,需要创建一个基本的Maven项目。
2. 添加Spring MVC依赖项到pom.xml文件中:
```xml
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.7</version>
</dependency>
</dependencies>
```
3. 创建一个HomeController类:
```java
package com.example.demo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HomeController {
@GetMapping("/")
public String home(Model model) {
model.addAttribute("message", "Hello, World!");
return "home";
}
}
```
4. 创建一个home.jsp文件:
```html
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>${message}</h1>
</body>
</html>
```
5. 创建一个WebConfig类:
```java
package com.example.demo;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.jsp().prefix("/WEB-INF/views/").suffix(".jsp");
}
}
```
6. 创建一个web.xml文件:
```xml
<web-app>
<display-name>Spring MVC Application</display-name>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/springmvc-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
```
7. 创建一个springmvc-config.xml文件:
```xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.example.demo" />
<mvc:annotation-driven />
<mvc:view-controller path="/" view-name="home" />
</beans>
```
8. 将home.jsp文件放在/WEB-INF/views/目录下。
9. 运行应用程序,并在浏览器中访问http://localhost:8080/。您应该能够看到“Hello, World!”消息。
这是一个简单的Spring MVC示例,它展示了如何使用Spring框架构建一个Web应用程序。当然,Spring框架有很多其他功能和用例,这只是一个入门示例。