1.首先要引入SpringMVC的jar包(由Spring框架提供)。
建议把所有的spring下载好的jar包全部拷贝到项目中。
2.配置前端控制器(配置一个中央处理器,是把所有的请求都转到该控制器上做处理)。
配置在web.xml里
<!-- 配置前端控制器 -->
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>springmvc3.1</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>springmvc2</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc2</servlet-name>
<url-pattern>*.action</url-pattern><!--配置的访问路径,一定是按照这种格式写 -->
</servlet-mapping>
</web-app>
3.创建springmvc.xml代码如下:
<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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
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"
default-autowire="byName"
>
</beans>
4.配置注解映射器和适配器:
<!-- 配置注解映射器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean>
<!-- 配置注解适配器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean>
<context:annotation-config>
<mvc:annotation-driven>
</mvc:annotation-driven>
</context:annotation-config>
5.编写相应的handler处理,需要给每个handler加入Controller的注解,方式如下:
package com.action;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class UserAction {
@RequestMapping(value="/getalluser.action")
public ModelAndView getAllUser(){
ModelAndView model= new ModelAndView();
model.addObject("ha","hhhihihhishfoihd");
model.setViewName("/index.jsp");
return model;
}
}
6.需要将编写的action或者说是handler加入到spring容器里:
<context:component-scan base-package="com.action"></context:component-scan>