Signup/Sign In

Servlet: HttpSessionEvent and HttpSessionListener

HttpSessionEvent class gives notifications for changes to sessions within a web application. HttpSessionListener receives notifications of changes to the list of active sessions in a web application and perform some action. HttpSessionListener is used to perform some important tasks when a session is created or destroyed. For example: counting the number of active session.

Servlet: Some other Session related Listeners

HttpSessionActivationListenerLet's you know when a session moves from one Virtual machine to another.
HttpSessionBindingListenerLe's your attribute class object get notified when they are added or removed from session.
HttpSessionAttributeListenerLet's you know when any attribute is added, removed or replaced in a session.

Methods of HttpSessionListener

void sessionCreated(HttpSessionEvent e) notification that a session was created.
void sessionDestroyed(HttpSessioEvent e)notification that a session was destroyed.

Example of HttpSessionListener

In this example we will create a session listener that will count the number of active sessions in a web application.

import javax.servlet.http.*;

public class MySessionCounter implements HttpSessionListener {

    private static int sessionCount; 
    public int getActiveSession()
        return sessionCount;
    public void sessionCreated(HttpSessionEvent e) 

    public void sessionDestroyed(HttpSessionEvent e) 


<web-app ...>