Servlets · Lesson 9
Servlet Listeners
Listening to Servlet Events
A servlet listener reacts when the web application, a session, or a request changes state. Listeners are useful for initialization, cleanup, metrics, and auditing because they observe lifecycle events without modifying every servlet. They should remain lightweight and predictable.
Application Listener Example
ServletContextListener receives callbacks when the application starts and stops. Store shared, read-only configuration in the servlet context rather than using mutable global variables.
import jakarta.servlet.ServletContextEvent;
import jakarta.servlet.ServletContextListener;
import jakarta.servlet.annotation.WebListener;
@WebListener
public class ApplicationStartupListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent event) {
String environmentName = System.getenv().getOrDefault("APP_ENV", "development");
event.getServletContext().setAttribute("environmentName", environmentName);
}
@Override
public void contextDestroyed(ServletContextEvent event) {
event.getServletContext().removeAttribute("environmentName");
}
}
Listener Types
| Listener | Observes | Typical use |
|---|---|---|
ServletContextListener | Application start and stop | Configuration and resource setup |
HttpSessionListener | Session creation and destruction | Active-user metrics |
ServletRequestListener | Request start and end | Request timing |
HttpSessionAttributeListener | Session attribute changes | Audit or diagnostics |
Common Mistake and Practices
Common Mistake: Performing slow database migrations or network calls directly in a listener callback. Application startup can fail or become difficult to diagnose when a listener blocks the container.
- Keep callbacks short and observable.
- Release resources during shutdown.
- Avoid mutable static state.
- Make initialization idempotent where possible.
- Log failures with enough context to troubleshoot them.
Real-World Use Case
A listener initializes an application-wide metrics registry when Tomcat starts and records the active session count as sessions are created and destroyed. The servlets remain focused on handling business requests.
Quiz Check