springmvc之DispatcherServlet
1、作用:DispatcherServlet是前置控制器,配置在web.xml(因为DispatcherServlet是一个servelet)文件中的。拦截匹配的请求,Servlet拦截匹配规则要自已定义(<servlet-mapping>的<url-pattern>中配置),把拦截下来的请求依据相应的规则分发到目标Controller来处理,是配置spring MVC的第一步。
2、web.xml中的配置
<servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
1)DispatcherServlet的配置就是servlet的配置,<servlet-name>、<servlet-class>、<load-on-startup>分别代表servlet名称、类路径、加载次序,<servlet-mapping>中的<url-pattern>配置拦截匹配规则。
2)springmvc是servlet的名字,多个DispatcherServlet通过名字来区别,每一个DispatcherServlet有自己的WebApplicationContext上下文对象,在DispatcherServlet的初始化过程中,框架会在web应用的 WEB-INF文件夹下寻找名为[servlet-name]-servlet.xml (本文的上下文文件名为springmvc-servlet.xml)的配置文件,生成文件中定义的bean。
3)WebApplicationContext上下文文件的配置可以有多种方法,需要配置<init-param>参数
a、不写,使用默认值:/WEB-INF/[servlet-name]-servlet.xml
b、<param-value>/WEB-INF/classes/springMVC.xml</param-value>
c、<param-value>classpath*:springMVC-mvc.xml</param-value>
注:多个值用逗号分隔
如下:
<servlet> <servlet-name>springmvc1</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/springmvc-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc1</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
3、上面用到的上下问文件如下
<?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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" 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-3.0.xsd"> <context:component-scan base-package="com.controller"/> <mvc:annotation-driven/> <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> <property name="redirectHttp10Compatible" value="false" /> </bean> </beans>