🎯 Why Use Listeners?
They let you hook into the lifecycle of:
- The ServletContext (entire app)
- HttpSession (per user)
- ServletRequest (per request)
You use them to:
- Initialize or clean up resources (e.g. DB pools)
- Log application or session events
- Track user sessions
- Inject defaults or track attribute changes
- Implement analytics or custom metrics
🔧 Types of Listeners (Servlet API)
Listener Interface | Listens To | When to Use |
---|---|---|
ServletContextListener | App start and stop | Initialize app-wide resources (e.g. DB, caches) |
HttpSessionListener | Session create/destroy | Track logged-in users, cleanup session data |
ServletRequestListener | Request start/end | Logging, timing, diagnostics |
ServletContextAttributeListener | Attribute added/removed in context | Global config changes or plugin loading |
HttpSessionAttributeListener | Session attribute change | Track login/logout events, cart changes, etc. |
ServletRequestAttributeListener | Request attribute change | For internal middleware logic (rarely used directly) |
🧪 Example: Tracking Active Sessions
@WebListener
public class SessionCounterListener implements HttpSessionListener {
private static int activeSessions = 0;
public void sessionCreated(HttpSessionEvent se) {
activeSessions++;
System.out.println("Session created. Active sessions: " + activeSessions);
}
public void sessionDestroyed(HttpSessionEvent se) {
activeSessions--;
System.out.println("Session destroyed. Active sessions: " + activeSessions);
}
}
🚀 Example: Initializing Resources on App Startup
@WebListener
public class AppStartupListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent sce) {
System.out.println("App started");
// Initialize DB connection, load config, etc.
}
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("App shutting down");
// Cleanup resources
}
}
🛠️ Registering Listeners
1. Using Annotations:
@WebListener
public class MyListener implements HttpSessionListener { ... }
2. Using web.xml
:
<listener>
<listener-class>com.myapp.MyListener</listener-class>
</listener>
✅ Summary
Listener Type | Best For |
---|---|
ServletContextListener | App-level setup & teardown |
HttpSessionListener | Tracking sessions, auth, cleanup |
ServletRequestListener | Request-level timing/logging |
AttributeListeners | Reacting to changes in session/context/request |