Quick revision
The short answer
Servlet listeners are callbacks the container calls when something happens in the web application's life. A ServletContextListener is told when the application starts and stops, which makes it the place to set up and tear down application-wide resources; an HttpSessionListener is told when a session is created and destroyed; and a ServletRequestListener is told when each request starts and ends. Spring's ContextLoaderListener is a ServletContextListener that starts the root application context in classic war deployments.
What to remember
In this answer, we saw that servlet listeners are callbacks the container calls on lifecycle events. ServletContextListener receives application startup and shutdown, which suits shared resources; HttpSessionListener receives session creation and destruction, including timeouts; ServletRequestListener receives the start and end of every request; and attribute listeners hear attribute changes. Spring's ContextLoaderListener is a ServletContextListener that starts and closes the root application context in classic wars, and in Spring Boot listeners are registered as beans or with ServletListenerRegistrationBean.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Servlet listeners are callbacks the container calls when something happens in the web application's life. A ServletContextListener is told when the application starts and stops, which makes it the place to set up and tear down application-wide resources; an HttpSessionListener is told when a session is created and destroyed; and a ServletRequestListener is told when each request starts and ends. Spring's ContextLoaderListener is a ServletContextListener that starts the root application context in classic war deployments.
Why this question is asked
Listeners are the quiet part of the Servlet API: filters and servlets get all the attention, but listeners are how a web application learns that it is starting, stopping, or gaining and losing sessions. Interviewers ask about them because they explain how frameworks like Spring bootstrap inside a container, and because they are the right tool for a few jobs that people often solve awkwardly elsewhere. In this answer, we will recap what a listener is, look at the three main listener types with an example each, see how Spring's ContextLoaderListener uses one, and see how listeners are registered in Spring Boot.
1A Quick Recap: What a Listener Is
A listener is an object that implements one of the listener interfaces from jakarta.servlet or jakarta.servlet.http. We register it with the container, and the container calls its methods when the matching event happens. Unlike a filter or a servlet, a listener does not handle requests; it reacts to lifecycle events.
There are listeners for three scopes, matching the three scopes of attributes in a web application: the whole application (the ServletContext), one user's session (the HttpSession), and one request (the ServletRequest). For each scope there is a lifecycle listener and an attribute listener that hears when attributes are added, replaced or removed.
| Listener | Events | Typical use |
|---|---|---|
ServletContextListener | contextInitialized, contextDestroyed | Start and stop app-wide resources |
HttpSessionListener | sessionCreated, sessionDestroyed | Count active sessions, clean up per-user state |
ServletRequestListener | requestInitialized, requestDestroyed | Per-request timing or context set-up |
...AttributeListener | attributeAdded, Replaced, Removed | React to attribute changes in a scope |
2ServletContextListener: Application Startup and Shutdown
contextInitialized is called once when the application starts, before any filter or servlet handles a request. contextDestroyed is called once when it stops, after the servlets and filters have been destroyed. That makes it the natural place to create something the whole application shares, such as a scheduler or a connection pool in a plain servlet application, and to close it again.
Notice why the shutdown half matters. In a container that hosts several applications, an undeployed application whose threads are still running cannot be garbage-collected, and Tomcat warns about it in its log. The listener is where we stop them.
3HttpSessionListener: Sessions Created and Destroyed
An HTTP session is the server-side state the container keeps for one user across requests, identified by a cookie such as JSESSIONID. sessionCreated is called when the container creates a session, which happens when code first calls request.getSession(). sessionDestroyed is called when the session is invalidated, for example at logout, or when it times out after a period of inactivity, 30 minutes by default in many containers. A timed-out session is destroyed by the container's background check, so the event may arrive a little after the exact timeout.
The counter is an AtomicInteger because sessions are created and destroyed on many threads at once. A session listener is also the right place to clean up anything we stored outside the session for that user, such as a temporary file, when the session ends. With a distributed session store such as Spring Session, the store publishes its own session events instead; check how your session setup reports them.
4ServletRequestListener: Every Request
requestInitialized is called when a request enters the application and requestDestroyed when it leaves. It is useful for light per-request work that does not need to change the request or response, such as measuring timing. For anything that must wrap, modify or reject a request, a filter is the better tool, because a listener cannot stop a request or replace its objects. Spring itself uses a request listener, RequestContextListener, in some setups to expose the current request to request-scoped beans.
5How Spring's ContextLoaderListener Uses One
In a classic Spring MVC war, the application has a root application context with services and repositories, and a child context per DispatcherServlet with controllers. ContextLoaderListener is a ServletContextListener. In contextInitialized it creates and refreshes the root context, reading its configuration from a context parameter or from a WebApplicationInitializer, and stores it as a ServletContext attribute where DispatcherServlet finds it and uses it as its parent. In contextDestroyed it closes that context, which runs every bean's destroy callbacks.
That is the listener idea in action: the container tells the application it is starting, and Spring uses that moment to start its own container. A Spring Boot application with an embedded server does not need ContextLoaderListener, because Boot creates the application context first and then starts the server itself.
6Registering Listeners in Spring Boot
A listener can be registered with @WebListener (scanned with @ServletComponentScan in Boot), with a listener element in web.xml, or programmatically with servletContext.addListener. In Spring Boot, the usual way is to declare it as a bean: Boot registers beans that implement the supported listener interfaces with the embedded container automatically, or we can wrap one in a ServletListenerRegistrationBean for explicit control.
For application startup work in Boot, Spring's own events are often a better fit than a ServletContextListener: an @EventListener for ApplicationReadyEvent runs when the whole application, including the web server, is ready, and beans can use @PreDestroy for shutdown.
7Follow-up questions
What is the difference between a listener and a filter?
A filter sits in the request path: it is called for matching requests, can modify the request and response, and decides whether the request continues by calling chain.doFilter. A listener is only notified of events, application start and stop, session creation and destruction, request start and end, and cannot block or change the processing. We use filters for request handling concerns and listeners for lifecycle concerns.
In what order are ServletContextListeners called?
contextInitialized is called in the order the listeners were declared, and contextDestroyed in reverse order, so a listener that depends on another one's resource is shut down before it.
Is sessionDestroyed called when the server is shut down?
For in-memory sessions, the container usually destroys or persists sessions on shutdown, and the behaviour differs between containers and configurations, for example Tomcat can persist sessions across restarts. We should not rely on sessionDestroyed for critical clean-up at shutdown; contextDestroyed is the reliable hook there.
8Conclusion
In this answer, we saw that servlet listeners are callbacks the container calls on lifecycle events. ServletContextListener receives application startup and shutdown, which suits shared resources; HttpSessionListener receives session creation and destruction, including timeouts; ServletRequestListener receives the start and end of every request; and attribute listeners hear attribute changes. Spring's ContextLoaderListener is a ServletContextListener that starts and closes the root application context in classic wars, and in Spring Boot listeners are registered as beans or with ServletListenerRegistrationBean.
Open with
Listeners are callbacks the servlet container invokes on lifecycle events, rather than components that handle requests. There is one per scope. A ServletContextListener gets contextInitialized when the application starts, before any request is served, and contextDestroyed when it stops, so I use it to create and close application-wide resources, like a scheduler or a pool in a plain servlet application, making sure threads are stopped so an undeploy does not leak.
Then, if they want more
An HttpSessionListener gets sessionCreated when a session is first created, and sessionDestroyed when it is invalidated at logout or times out; it is good for counting active sessions or cleaning up per-user resources, and I would use an atomic counter because these events happen on many threads.
A ServletRequestListener gets requestInitialized and requestDestroyed for every request, useful for light work like timing, but if I need to change or reject a request I use a filter instead. There are also attribute listeners for each scope.
The best-known listener is Spring's ContextLoaderListener: in a classic war it is a ServletContextListener that creates the root application context on startup, stores it in the ServletContext where DispatcherServlet uses it as the parent, and closes it on shutdown.
In Spring Boot with an embedded server, Boot creates the context itself, and I register listeners simply as beans or with a ServletListenerRegistrationBean. For startup logic in Boot I usually prefer an ApplicationReadyEvent listener.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Jakarta EE specifications
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "What are servlet listeners such as ServletContextListener and HttpSessionListener used...": https://scrivio-interview-library.netlify.app/java/servlets/7af0fe10b8/