SSM框架中,ContextLoaderListener与RequestContextListener的联系与区别

  在整合SSM框架时,我们要在web.xml文件中对spring进行相关配置。

  首先要配置一个<context-param></context-param>

  

<!--加载spring容器-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
      classpath:spring/spring-*.xml,
    </param-value>
  </context-param>

  同时还要配置两个listener,分别是ContextLoaderListener和RequestContextListener。

<!--配置监听器,来加载spring容器    只负责监听web容器启动和关闭的事件-->
   <listener>
     <listener-class>
       org.springframework.web.context.ContextLoaderListener
     </listener-class>
   </listener>
<!--随时获得request   监听HTTP请求事件    Web服务器收到的每次请求都会通知该监听器-->
  <listener>
    <listener-class>
      org.springframework.web.context.request.RequestContextListener
    </listener-class>
  </listener>

  那么这两个监听器有什么关系呢?其中ContextLoaderListener只负责监听web容器的启动和关闭,而web服务器收到的每次请求都会通知RequestContextListener这个监听器。在整合spring容器时使用ContextLoaderListener,它实现了ServletContextListener监听器接口,ServletContextListener只负责监听web容器启动和关闭的事件。而RequestContextListener实现ServletRequestListener监听器接口,该监听器监听HTTP请求事件,web服务器接收的每一次请求都会通知该监听器。spring容器启动和关闭操作由web容器的启动和关闭事件触发,但如果spring容器中的Bean需要request,session,globalsession作用域的支持,spring容器本身就必须获得eb容器的HTTP请求事件,以HTTP请求的事件”驱动”Bean作用域的控制逻辑。也就是说只有配置了RequestContextListener,spring容器中的bean才能与到request、session、globalSession中的数据进行交互!

原文地址:https://www.cnblogs.com/1102whw/p/11302276.html