SpringMVC开发案例
时间: 2024-06-09 21:08:14 浏览: 114
以下是一个简单的 SpringMVC 开发案例:
1. 创建一个 Maven 项目并添加 SpringMVC 依赖:
```xml
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.9</version>
</dependency>
```
2. 配置 web.xml 文件:
```xml
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/spring-mvc-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
```
3. 创建 Spring MVC 配置文件 spring-mvc-config.xml:
```xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
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.controller" />
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
```
4. 创建一个控制器类:
```java
@Controller
public class HelloWorldController {
@RequestMapping("/hello")
public String helloWorld(Model model) {
model.addAttribute("message", "Hello, World!");
return "hello-world";
}
}
```
5. 创建一个 JSP 视图文件:
```html
<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h1>${message}</h1>
</body>
</html>
```
6. 启动应用程序并在浏览器中访问 http://localhost:8080/hello。
以上是一个简单的 SpringMVC 开发案例,可以帮助你了解 SpringMVC 的基本使用。
阅读全文