zoukankan      html  css  js  c++  java
  • ContextLoaderListener与DispatcherServlet所加载的applicationContext的区别

    spring通过在web.xml 中配置ContextLoaderListener 来加载context配置文件,在DispatcherServlet中也可以来加载spring context配置文件,那么这两个有什么区别呢。

    ContextLoaderListener中加载的context成功后,spring 将 applicationContext存放在ServletContext中key值为"org.springframework.web.context.WebApplicationContext.ROOT"的attribute 中。 (servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context));可以通过 WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext) 或WebApplicationContextUtils.getWebApplicationContext(servletContext)方法来获取对应的applicationContext。

    DispatcherServlet加载的context成功后,如果 publishContext属性的值设置为true的话(缺省为true) 会将applicationContext存放在 org.springframework.web.servlet.FrameworkServlet.CONTEXT. + (servletName)的attribute中。

    例如 web.xml中配置如下 

    Xml代码  

        <servlet>  
            <servlet-name>mvcServlet</servlet-name>  
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
            <init-param>  
                <param-name>contextConfigLocation</param-name>  
                <param-value>classpath*:/spring/config/applicationContextMVC.xml</param-value>  
            </init-param>  
            <load-on-startup>1</load-on-startup>  
        </servlet> 

    则对应的applicationContext的attribute key值为org.springframework.web.servlet.FrameworkServlet.CONTEXT.mvcServlet。

      在每次request请求时,DispatcherServlet会将此applicationContext存放在request中attribute 值为 org.springframework.web.servlet.DispatcherServlet.CONTEXT中 (request.setAttribute(WEB_APPLICATION_CONTEXT_ATTRIBUTE,getWebApplicationContext());)。可以通过 RequestContextUtils.getWebApplicationContext 或 WebApplicationContextUtils.getWebApplicationContext(servletContext,attrname) 方法 来获取对应的applicationContext。

      从上面的分析可以看出,DispatcherServlet所加载的applicationContext可以认为是mvc私有的context,由于保存在servletContext中的key值与通过ContextLoaderListener加载进来的applicationContext使用的 key值不相同,因此如果只使用DispatcherServlet加载context的话,如果程序中有地方使用 WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext) 来试图获取applicationContext时,就会抛出"No WebApplicationContext found: no ContextLoaderListener registered?"的exception。

  • 相关阅读:
    Linux 下面安装 nginx 以及进行TCP反向代理、负载均衡的过程
    AMD全新32核线程撕裂者GeekBench跑分曝光:超2950X近一倍
    Win7 & VS2013 编译 WebKit 总结
    窗宽窗位与其处理方法
    编写Delphi控件属性Stored和Default的理解及应用
    vSphere、Hyper-V与XenServer 你选哪个?
    写给那些常年战痘的痘友们~~~
    怎么解决xp系统不能安装NET Framework4.0?
    Kali Linux渗透基础知识整理(四):维持访问
    解决vista和win7在windows服务中交互桌面权限问题:穿透Session 0 隔离
  • 原文地址:https://www.cnblogs.com/eastson/p/3904713.html
Copyright © 2011-2022 走看看