Search code examples
springlistenerweb.xml

What do ContextLoaderListener and RequestContextListener do?


I have an application, where i am using Spring. And in my web.xml i use lines below

<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>

What are they ? Are they mandatory ?


Solution

  • org.springframework.web.context.ContextLoaderListener is a class from Spring framework. As it implements the ServletContextListener interface, the servlet container notifies it at startup (contextInitialized) and at shutdown (contextDestroyed) of a web application.

    It is specifically in charge of bootstrapping (and orderly shutdown) the Spring ApplicationContext.

    Ref: javadoc says:

    Bootstrap listener to start up and shut down Spring's root WebApplicationContext. Simply delegates to ContextLoader as well as to ContextCleanupListener.

    org.springframework.web.context.request.RequestContextListener is another class from same framework. Its javadoc says:

    Servlet 2.4+ listener that exposes the request to the current thread, through both LocaleContextHolder and RequestContextHolder. To be registered as listener in web.xml.

    Alternatively, Spring's RequestContextFilter and Spring's DispatcherServlet also expose the same request context to the current thread. In contrast to this listener, advanced options are available there (e.g. "threadContextInheritable").

    This listener is mainly for use with third-party servlets, e.g. the JSF FacesServlet. Within Spring's own web support, DispatcherServlet's processing is perfectly sufficient.

    So it is normally not used in a Spring MVC application, but allows request or session scoped bean in a JSF application using a Spring ApplicationContext