Master Core Java & Servlets!
Subscribe to Ram N Java for beginner-friendly coding walkthroughs, web architecture lessons, and hands-on Java guides!
🔔 Subscribe to Ram N JavaTracking Logged-In Users with HttpSessionListener
In Java web applications, tracking the number of active sessions or concurrent logged-in users is a common requirement for dashboards, system monitoring, and session management. The standard, cleanest way to achieve this is by implementing the HttpSessionListener interface.
The web container automatically triggers callback methods on HttpSessionListener whenever a new HTTP session is created or an existing session is invalidated or times out. By updating a counter stored in the application-wide ServletContext, you can maintain an accurate, real-time count of active users.
How the Listener Works
The HttpSessionListener interface defines two primary lifecycle methods:
- sessionCreated(HttpSessionEvent se): Invoked automatically when a new user session is initiated. Here, you increment the active user counter.
- sessionDestroyed(HttpSessionEvent se): Invoked when a user logs out (session invalidated) or when the session expires due to inactivity. Here, you decrement the counter.
@WebListener
public class UserCounterListener implements HttpSessionListener {
private static int activeUsers = 0;
public void sessionCreated(HttpSessionEvent se) {
activeUsers++;
se.getSession().getServletContext().setAttribute("activeUsers", activeUsers);
}
public void sessionDestroyed(HttpSessionEvent se) {
activeUsers--;
se.getSession().getServletContext().setAttribute("activeUsers", activeUsers);
}
}
Key Advantages of Using HttpSessionListener
- Automatic Session Lifecycle Management: No manual tracking or polling needed; the servlet container notifies the listener on lifecycle transitions.
- Clean Separation: Decouples session analytics and user counting from individual business servlets.
- Global Availability: Storing the count inside
ServletContextmakes it effortlessly accessible across all servlets, JSPs, and controllers.
Recommended Related Tutorials
Continue exploring servlet listeners and session handling with these tutorials from Ram N Java:
Click here to watch in Youtube : https://www.youtube.com/watch?v=fv8Idtevcg0
Click the below Image to Enlarge
HttpSessionListenerDemo Project Dir Structure


No comments:
Post a Comment