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

ListenerDescription
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

MethodsDescription
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.


MySessionCounter.java

import javax.servlet.http.*;

public class MySessionCounter implements HttpSessionListener {

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

    public void sessionDestroyed(HttpSessionEvent e) 
    {
        sessionCount--;
    }
}

web.xml

<web-app ...>
    <listener>
        <listener-class>MySessionCounter</listener-class>
    </listener>
</web-app>