ContextLoaderListener和RequestContextListener有什么作用?

moo*_*sel 6 spring web.xml listener

我有一个应用程序,我在使用Spring.在我的web.xml中,我使用下面的行

<web-app>
     ....
     <listener>
          <listener-class>
             org.springframework.web.context.ContextLoaderListener
          </listener-class>
       </listener>
       <listener>
          <listener-class>
             org.springframework.web.context.request.RequestContextListener
          </listener-class>
       </listener>
       ....
</web-app>
Run Code Online (Sandbox Code Playgroud)

这些是什么 ?这是强制性的吗?

Ser*_*sta 6

org.springframework.web.context.ContextLoaderListener是一个来自Spring框架的类.在实现ServletContextListener接口时,servlet容器在web应用程序的startup(contextInitialized)和shutdown(contextDestroyed)处通知它.

它专门负责Spring ApplicationContext的引导(并有序关闭).

参考:javadoc说:

Bootstrap监听器启动并关闭Spring的根WebApplicationContext.只需委托ContextLoader和ContextCleanupListener.

org.springframework.web.context.request.RequestContextListener是来自同一框架的另一个类.它的javadoc说:

Servlet 2.4+监听器,通过LocaleContextHolder和RequestContextHolder向当前线程公开请求.要在web.xml中注册为侦听器.

或者,Spring的RequestContextFilter和Spring的DispatcherServlet也向当前线程公开相同的请求上下文.与此侦听器相比,那里提供了高级选项(例如"threadContextInheritable").

此侦听器主要用于第三方servlet,例如JSF FacesServlet.在Spring自己的Web支持中,DispatcherServlet的处理就足够了.

因此它通常不在Spring MVC应用程序中使用,但允许使用Spring ApplicationContext在JSF应用程序中使用请求或会话范围的bean