javax.servlet.http.HttpSessionListener is an interface which provides the implementing class a capability to keep track of HTTP Session life cycle events.

In this post, I’ll demonstrate with the help of a demo project, how to count active HTTP Sessions using HttpSessionListener interface. I’ve used Tomcat as the web container to deploy this demo project.

Create a dynamic web project (Select web module version 3.0) in Eclipse with the following structure

Choose web module version 3
Create project in Eclipse
Note
The Dynamic Web Module version describes the used Servlet API version. The 3.0 version uses Servlet API version 3.0 and the version 2.5 uses the Servlet API version 2.5. The newer version has some new features.

The class SessionCounter.java has the following two methods inherited from the interface javax.servlet.http.HttpSessionListener

  • sessionCreated(HttpSessionEvent sessionEvent)
  • – called when a session is created.

  • sessionDestroyed(HttpSessionEvent sessionEvent)
  • – called when a session is invalidated (or in other words, destroyed).

    The member variable private static int sessionCount keeps track of all the sessions being created and destroyed. Following is the source code for it

    SessionCounter.java
    package com.planetofbits.demo.listener;
    
    import javax.servlet.annotation.WebListener;
    import javax.servlet.http.HttpSessionEvent;
    import javax.servlet.http.HttpSessionListener;
    
    /**
     * This class listens to all the sessions being created and destroyed
     * 
     * @author www.planetofbits.com
     */
    @WebListener
    public class SessionCounter implements HttpSessionListener
    {
    	// Counter for number of active sessions
    	private static int sessionCount = 0;
    
    	@Override
    	public void sessionCreated(HttpSessionEvent sessionEvent)
    	{
    		// Increment when a session is created
    		sessionCount++;
    	}
    
    	@Override
    	public void sessionDestroyed(HttpSessionEvent sessionEvent)
    	{
    		// Decrement when a session is destroyed
    		sessionCount--;
    	}
    
    	public static int getSessionCount()
    	{
    		// Return the count of active sessions
    		return sessionCount;
    	}
    
    }
    

    The index.jsp imports the SessionCounter.java and calls the static method getSessionCount() which returns the current count of the active HTTP sessions.

    index.jsp
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    	pageEncoding="ISO-8859-1"%>
    <%@ page import="com.planetofbits.demo.listener.SessionCounter"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Home Page</title>
    </head>
    <body>
    	<%
    		int sessionCount = SessionCounter.getSessionCount();
    	%>
    	<h3>Number of active sessions are: <%=sessionCount%></h3>
    </body>
    </html>
    

    The web.xml defines a session time-out value of 1 minute.

    web.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xmlns="http://java.sun.com/xml/ns/javaee"
    	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    	id="WebApp_ID" version="3.0">
    	
    	<display-name>HttpSessionListenerDemo</display-name>
    	
    	<welcome-file-list>
    		<welcome-file>index.jsp</welcome-file>
    	</welcome-file-list>
    	
    	<session-config>
    		<!-- Time-out the session after one minute -->
    		<session-timeout>1</session-timeout>
    	</session-config>
    
    </web-app>
    
    Note
    The <session-timeout> defines the time-out value in minutes.

    To understand the execution of the above code better, deploy and the run the project in different browsers sequentially. I’ve run it first in Firefox, then in Chrome and then in Internet Explorer. Open the following URL in browser http://localhost:8080/HttpSessionListenerDemo/index.jsp
    Please use the port number according to your server configuration.

    You’ll see that the each time the URL is invoked, a new session is created and the count increases.

    Firefox session count
    Chrome session count
    IE session count

    Now, wait for more than one minute and refresh any of these browser windows. You’ll see that the count of sessions has decreased. This is because the sessions start expiring after one minute of their creation time and when they expire, the sessionDestroyed() method of the session listener is called which decrements the count by one for each expired session.

    Count active HTTP Sessions using HttpSessionListener
                    

    Comments, Questions or Suggestions: