[Spring MVC]学习笔记--DispatcherServlet

在上一篇我们介绍了Servlet,这一篇主要来看一下MVC中用到的DispatcherServlet(继承自HttpServlet)。

1. DispatcherServlet在web.xml中被声明。

<web-app>

    <servlet>

        <servlet-name>example</servlet-name>

        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

        <load-on-startup>1</load-on-startup>

    </servlet>



    <servlet-mapping>

        <servlet-name>example</servlet-name>

        <url-pattern>/example/*</url-pattern>

    </servlet-mapping>



</web-app>

注:我们也可以在代码中去进行设置,具体参考http://docs.spring.io/spring/docs/4.0.6.RELEASE/spring-framework-reference/htmlsingle/#mvc-container-config

 

2. DispatcherServlet包含的一些beans

[Spring MVC]学习笔记--DispatcherServlet

 

3. 除了步骤2种默认提供的bean以外,Spring MVC还会在WEB-INF文件夹下寻找一个 [servlet-name]-servlet.xml 文件(步骤1中,会寻找example-servlet.xml这个文件), 创建这个文件中定义的beans。

如果需要修改默认的bean,可以在这个里面进行定义,加载时会覆盖默认的bean。

 

4. 我们可以通过DispatcherServlet中的初始化方法,配置步骤3中的xml的路径。

或者,如果你想用一个公用的xml,可以配置context-param并且不设置contextConfigLocation的值就可以了。

<web-app>

    <context-param>

        <param-name>contextConfigLocation</param-name>

        <param-value>/WEB-INF/root-context.xml</param-value>

    </context-param>

    <servlet>

        <servlet-name>dispatcher</servlet-name>

        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

        <init-param>

            <param-name>contextConfigLocation</param-name>

            <param-value></param-value>

        </init-param>

        <load-on-startup>1</load-on-startup>

    </servlet>

    <servlet-mapping>

        <servlet-name>dispatcher</servlet-name>

        <url-pattern>/*</url-pattern>

    </servlet-mapping>

    <listener>

        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

    </listener>

</web-app>

 

5. 如果要让mvc下的annotation起作用,需要在 [servlet-name]-servlet.xml 中增加一行。

<?xml version=1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

    xmlns:mvc="http://www.springframework.org/schema/mvc"

    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/mvc

        http://www.springframework.org/schema/mvc/spring-mvc.xsd">



    <mvc:annotation-driven />



</beans>

 

你可能感兴趣的:(spring mvc)