A simple HttpSessionListener example – active sessions counter

Here’s a simple “HttpSessionListener” example to keep track the total number of active sessions in a web application. If you want to keep monitor your session’s create and remove behavior, then consider this listener.

Java Source


package com.mkyong;

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class SessionCounterListener implements HttpSessionListener {

  private static int totalActiveSessions;
	
  public static int getTotalActiveSession(){
	return totalActiveSessions;
  }
	
  @Override
  public void sessionCreated(HttpSessionEvent arg0) {
	totalActiveSessions++;
	System.out.println("sessionCreated - add one session into counter");
  }

  @Override
  public void sessionDestroyed(HttpSessionEvent arg0) {
	totalActiveSessions--;
	System.out.println("sessionDestroyed - deduct one session from counter");
  }	
}

web.xml


<web-app ...>
        <listener>
		<listener-class>com.mkyong.SessionCounterListener</listener-class>
	</listener>
</web-app>

How it work?

– If a new session is created , e.g “request.getSession();” , the listener’s sessionCreated() will be executed.
– If a session is destroyed, e.g session’s timeout or “session.invalidate()”, the listener’s sessionDestroyed() will be executed.


  HttpSession session = request.getSession(); //sessionCreated() is executed
  session.setAttribute("url", "mkyong.com"); 
  session.invalidate();  //sessionDestroyed() is executed

20 comments on “A simple HttpSessionListener example – active sessions counter

  1. Hi Mkyong,

    I want to send user info between my EARs, I can send this information from a main webapp to the others webapp, the problem is how can I re-initialize timeout main webapp when I was doing some tasks in another webapp.

    Can you have some idea for this isssue?.

    Thanks in advance.

    Reply
  2. Sir i am working on a android project in which i have 5 activities in which one to five activity data is to carrried out and then on the fifth activity there is a submit button..when i click then the whole activities data is submitted in database so can you please help me to solve this problem……..

    Reply
  3. I am beginner in JavaWeb.I want to know,Why use

    30

    Please Help me.

    Reply
  4. hi,
    in my project i want to destroy all the session after i close browser. i want to use Hpptsessionlistener but i dont know how to implement. can you help me?
    thanks!

    Reply
  5. Hello,

    increasing and decreasing an int value in a multithreaded context must be at least synchronized.

    You could use a Lock (java concurrency) as well.

    Best regards and many thanx for all your tutorials.

    Reply
  6. Sir,

    I want to count number of sessions creating or deleting in my struts web application. I know servlet session listener. But i am unable to know how to create session listener for struts1.5 application.
    If any one know Help me please
    [email protected] is my mail id.

    Reply
  7. This code is half-working for me
    I am setting session.setMaxInactiveInterval(8) and wait 8 second after login. Code from method public void sessionDestroyed(HttpSessionEvent arg0){} isn’t executing automatically . I must click refresh in browser to make execute this code. I want to write to some data to database automatically when session is over.
    What is wrong?
    thanks in advance

    Reply
  8. Hi Mkyong,

    i want to do that when specific session is destroyed at that time i want to automatically redirect a user on login page. We can’t do that in a sessionDestroyed method of HttpSessionListener listener because we don’t have object for request and response. Is there any way except javascript and jquery then please tell me. Thanks in advance.

    Reply
    1. You probably solved this 4 years ago but the normal way to do this is some kind of servlet filter that checks the session and otherwise redirects you

      Reply
      1. Can you elaborate your method? Say I want to persist the data in a session just before it is destroyed, and I thought maybe I could send a request (e.g. forword(“saveItem”)) from the sessionDestroyed() method to invoke the action class (e.g. SaveItem) where the data would be persisted. But it couldn’t be done because there’s no way to get a request object in that method. So can you explain your “filter” approach. Thanks!

        Reply
  9. Hi ..

    In my project i have to show a alert type of message to user after 20 mins of his login into application.

    I need some thing which keep the track of user login time and after 20 mins it automatically should popup a alert message by saying “Your Session Time out . Want to Continue ?” some thing like this.

    let me know if any thing can be done.

    Thanks in advance
    Deepak Surthi

    Reply
  10. Do you know how to integrate it with Spring ? I mean, how to use dependency injection in your session listener. Thanks.

    Reply
      1. if session is having some details what can i do for session is not overriding previous details

        Reply
  11. You have a concurrency problem in the listener, consider using java.util.concurrent.atomic.AtomicInteger instead of int.

    Reply

Leave a Comment

Your email address will not be published. Required fields are marked *