Spring MVC-ContextLoaderListener和DispatcherServlet

Tomcat或Jetty作为Servlet容器会为每一个Web应用构建一个ServletContext用于存放所有的Servlet, Filter, Listener。Spring MVC 启动的时候主要涉及到DispatcherServlet 与 ContextLoaderListener。

关于ContextLoaderListener和DispatcherServlet
ContextLoaderListener
  1. ContextLoaderListener 作为一个Listener会首先启动,创建一个WebApplicationContext用于加载除Controller等Web组件以外的所有bean,这个ApplicationContext作为根容器存在,对于整个Web应用来说,只能存在一个,也就是父容器,会被所有子容器共享,子容器可以访问父容器里的bean,反过来则不行。
  2. A. XML配置下会直接创建ContextLoaderListener,然后在contextInitialized方法中初始化WebApplicationContext。
    B. 如果使用的是AnnotationConfig,则通过AnnotationConfigWebApplicationContext获取一个WebApplicationContext之后传给ContextLoadListener。
    之后再contextInitialized方法中调用父类ContextLoader的initWebApplicationContext进行初始化。
public class ContextLoader {
     /**
     * The root WebApplicationContext instance that this loader manages.
     */
    private WebApplicationContext context;

    public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
     this.context = createWebApplicationContext(servletContext);
     servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
     return this.context;
    }
}

可以看到ContextLoader作为ContextLoaderListener的父类在创建了WebApplicationContext之后(针对的是XML配置,使用contextConfigLocation参数指定的配置文件),会通过WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE这个属性将ApplicationContext保存到ServletContext之中,而ContextLoader在创建WebApplicationContext之前也会检查这个属性是否有关联的对象,保证了整个Servletcontext之中只会存在一个根WebApplicationContext。

DispatcherServlet
  1. 在加载了Listener,Filter之后,DispatcherServlet作为ServletContext之中很可能唯一的一个Servlet被初始化,作为整个Web应用的Front Controller进行请求转发。
  2. A. XML配置,生成默认的DispatcherServlet,init时通过init-param中的contextConfigLocation指定的配置文件创建WebApplicationContext。
    B.AnnotationConfig,通过AnnotationConfigWebApplicationContext读取JavaConfig后生成WebApplicationContext,传递给DispatcherServlet进行构造。
  3. DispatcherServlet构造完成之后,调用init方法进行初始化,将DispatcherServlet关联的WebApplicationContext的父容器设为之前ContextLoaderListener创建的WebApplicationContext。
  4. DispatcherServlet关联的WebApplicationContext会在请求到来的时候被设为request的attribute暴露给handlers和之后的web组件。

由此可知,对于一个使用SpringMVC构建的Web应用来说,ContextLoaderListener虽然只能加载一个根容器,但其实是可选的,而DispatcherServlet作为请求转发处理返回结果的核心是比不可少的,而且可以不唯一。
但在Web应用中还是建议使用这种分层的容器结构,更为清晰,也便于之后的扩展。

web.xml与Servlet3.0

传统的web.xml配置适用于Servlet3规范之前的Servlet容器,而Servlet3之后的Servlet容器可以使用注解或是Java代码的方式进行配置。
Servlet3.0环境中,容器会在classpath下寻找ServletContainerInitializer接口的实现类,用于配置Servlet容器。Spring的SpringServletContainerInitializer类就实现了这个接口,并会寻找WebApplicationInitializer接口的实现类完成上面两个组件的加载。

public interface WebApplicationInitializer {
    /**
     * Configure the given {@link ServletContext} with any servlets, filters, listeners
     * context-params and attributes necessary for initializing this web application. See
     * examples {@linkplain WebApplicationInitializer above}.
     * @param servletContext the {@code ServletContext} to initialize
     * @throws ServletException if any call against the given {@code ServletContext}
     * throws a {@code ServletException}
     */
    void onStartup(ServletContext servletContext) throws ServletException;
}

这个接口的两个主要实现基类为AbstractContextLoaderInitializer与AbstractDispatcherServletInitializer,分别负责将ContextLoaderListener与DispatcherServlet加载到ServletContext之中,但是这两个类分别获取WebApplicationContext的函数并没有实现,如果如需要,你可以通过自己实现通过XML获取WebApplicationContext,而Spring提供了一个AbstractAnnotationConfigDispatcherServletInitializer供你来继承,如名可知,是使用JavaConfig来加载WebApplicationContext的。
当然你也可以自己实现WebApplicationInitializer手动将Servlet和Listener这些加载如ServletContext。
强调:Servlet3.0容器会自己检查classpath下实现了ServletContainerInitializer的类,使用这个接口的onStartup函数进行ServletContext的初始化。如果不适用这个,那么就用传统的web.xml进行ContextLoaderListener与DispatcherServlet的装配。

强调

对于DispatcherServlet与ContextLoaderListener的配置分为web.xml与Servlet容器发现两种,而对于这两个组件的WebApplicationContext的配置也分为XML方式和JavaConfig方式。

  1. web.xml + application.xml =
<listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath*:config/spring-context.xml</param-value>
</context-param>
//<br/>
<servlet>
      <servlet-name>ebook-manage</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:config/spring-servlet.xml</param-value>
      </init-param>
      <load-on-startup>1</load-on-startup>
      <async-supported>true</async-supported>
</servlet>
<servlet-mapping>
        <servlet-name>ebook-manage</servlet-name>
        <url-pattern>/</url-pattern>
</servlet-mapping>
  1. web.xml + JavaConfig =
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.
➥ AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.habuma.spitter.config.RootConfig</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.
➥ AnnotationConfigWebApplicationContext
</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
com.habuma.spitter.config.WebConfigConfig
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
  1. ServletContainerInitializer(WebApplicationInitializer) + JavaConfig =
public class SpittrWebAppInitializer
extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { RootConfig.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { WebConfig.class };
}
}
  1. ServletContainerInitializer(WebApplicationInitializer) + application.xml =
    需要继承AbstractDispatcherServletInitializer然后自己实现通过application.xml加载ApplicationContext的函数。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 162,825评论 4 377
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,887评论 2 308
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 112,425评论 0 255
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,801评论 0 224
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 53,252评论 3 299
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 41,089评论 1 226
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,216评论 2 322
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 31,005评论 0 215
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,747评论 1 250
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,883评论 2 255
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,354评论 1 265
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,694评论 3 265
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,406评论 3 246
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,222评论 0 9
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,996评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 36,242评论 2 287
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 36,017评论 2 281

推荐阅读更多精彩内容