spring MVC开发步骤
- 把spring3提供的jar包拷贝到/WEB-INF/lib/目录下
- 在web.xml中进行spring3mvc的启动配置
web.xml放在/WEB-INF/目录下
配置模版:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
配置spring MVC的核心Servlet控制器
<servlet>
<servlet-name>spring</servlet-name>
<servletclass>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
- 创建servlet-name-servlet.xml的Action映射文件
说明:
1)该文件应放在/WEB-INF/目录下
2)servlet-name应为web.xml文件中的<servlet-name>标签值,本例为spring-servlet.xml
配置模版为:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
</beans>
配置action 采用spring mvc注解的方式把请求映射为相应的action对象中的方法来处理
<!-- 启用spring mvc 注解 -->
<context:annotation-config />
<!-- 设置使用注解的类所在的jar包 -->
<context:component-scan base-package="com.zte"></context:component-scan>
<!-- 完成请求和注解POJO的映射 -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<!-- 对转向页面的路径解析。prefix:前缀, suffix:后缀 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/page/" />
<property name="suffix" value=".jsp" />
</bean>
- 编写spring MVC Action程序
package com.zte.action;
@Controller //类似Struts的Action
public class TestController {
@Resource(name = "loginService")
private LoginService loginService;
@RequestMapping("/login.do")
public String regLogin(User user) {
System.out.println("HelloController.handleRequest()");
loginService.add(user);
return "success";}
}
网友评论