Spring ContextLoaderListener和RequestContextListener做什么?

Spring ContextLoaderListener和RequestContextListener做什么?,spring,listener,web.xml,Spring,Listener,Web.xml,我有一个应用程序,我正在使用Spring。 在我的web.xml中,我使用下面的行 <web-app> .... <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </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>

....
org.springframework.web.context.ContextLoaderListener
org.springframework.web.context.request.RequestContextListener
....
它们是什么?
它们是必需的吗?

侦听器通常是容器通知应用程序事件的一种方式,而不仅仅是web请求

例如,要在会话即将超时时收到通知,您需要扩展HttpSessionListener并实现sessionDestroyed()方法。然后,容器将在会话到期时调用该函数,您可以将其与该用户的登录时间一起记录

对于ContextLoaderListener,这可以让您启动应用程序中与web无关的部分,而不是等待某人点击您的spring组件。它使用前面在web.xml中设置的上下文参数contextConfigLocation来知道要启动什么

对于RequestContextListener,您会收到创建和删除请求的通知


它们是否必要取决于应用程序的体系结构。

org.springframework.web.context.ContextLoaderListener
是Spring framework中的一个类。当servlet容器实现
ServletContextListener
接口时,它会在web应用程序启动(
contextInitialized
)和关闭(
contextDestroyed
)时通知它

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

参考:javadoc说:

引导侦听器启动和关闭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的处理就足够了


因此,它通常不用于SpringMVC应用程序,而是允许在JSF应用程序中使用请求或会话范围的bean(使用SpringApplicationContext)

为什么要添加它们呢?您只是复制粘贴了其他人的代码,而没有阅读与之相关的文档吗?@BalusC,我已经尝试深入到一个示例中并理解其中的每一部分:)我目前对此有一个问题,假设RequestContextListener在xml配置中为“/”所有http请求提供了一个筛选器映射,并且我使用scope=“session”对于一个在url请求期间未被调用但仅用于身份验证以调用另一个服务的aop配置调用的bean,到那时requestContextListener实际上错过了它,因此scope=“session”bean将导致一个错误,称其会话在当前服务中不可用thread@marked. 恐怕我不能用简单的评论来回答这个问题。嗯,你最好问一个新问题,并把这个问题作为你研究的参考。这样,您就可以在配置中添加更多的上下文和详细信息。如果你没有得到足够的答案,请随时给我留言。