1.配置
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:SpringMybatisConfiguration.xml</param-value>
</context-param>
<servlet>
<servlet-name>dispatch</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:test-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatch</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
值得注意的是需要将MVC相关的配置提取在*-servert.xml中,将业务核心逻辑类相关配置文件放在如下配置中。
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:SpringMybatisConfiguration.xml</param-value>
</context-param>
这么做可以有很好的分层的效果。当然也可以将所有的配置都放在DispatcherServlet中,而删除以下配置,很不推荐。
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:SpringMybatisConfiguration.xml</param-value>
</context-param>
2.用途
Spring MVC的核心类。
3. 结构
DispatcherServlet extends FrameworkServlet extends HttpServletBean extends HttpServlet
4. 初始化
一般配置为servlet容器启动时就进行init:<load-on-startup>1</load-on-startup>,否则将在初次访问时进行init。
HttpServletBean.init()
FrameworkServlet.initServletBean()
FrameworkServlet.initWebApplicationContext():根据配置文件(由<param-name>contextConfigLocation</param-name>指定)初始化一个WebApplicationContext,值得注意的是该WebApplicationContext的父容器是org.springframework.web.context.ContextLoaderListener初始化的WebApplicationContext。一般来说我们会把负责业务逻辑配置文件由ContextLoaderListener来加载,将MVC相关的配置文件由DispatcherServlet来加载。实现比较好的解耦。
DispatcherServlet.onRefresh(ApplicationContext context)
DispatcherServlet.initStrategies(ApplicationContext context):完成了DispatcherServlet核心功能的装配,如果用户没有配置,则使用默认的:/org/springframework/web/servlet/DispatcherServlet.properties