springmvc入门程序
时间: 2024-01-16 16:13:30 浏览: 67
springmvc入门
以下是Spring MVC入门程序的步骤:
1. 创建Maven项目,并添加Spring MVC依赖
2. 在web.xml文件中配置DispatcherServlet
```
<web-app>
<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/dispatcher-servlet.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
```
3. 创建dispatcher-servlet.xml文件并配置相关的bean
```
<beans xmlns="http://www.springframework.org/schema/beans"
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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.example.controller" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
```
4. 创建Controller类并添加相关方法
```
@Controller
public class HelloWorldController {
@RequestMapping("/helloWorld")
public ModelAndView helloWorld() {
String message = "Hello World, Spring MVC!";
return new ModelAndView("helloWorld", "message", message);
}
}
```
5. 创建JSP页面并添加相关内容
```
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
```
6. 运行程序并访问http://localhost:8080/项目名/helloWorld即可看到页面显示“Hello World, Spring MVC!”的结果。
阅读全文