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

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
Fran├žois-Xavier Robin
Guest
Fran├žois-Xavier Robin

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.

jeevan
Guest
jeevan

iam using appconfig.java file i dont have web.xml

Adrian
Guest
Adrian

well done !!

Zephyrv
Guest
Zephyrv

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.

Asif
Guest
Asif

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

Rafiqul Islam
Guest
Rafiqul Islam

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

30

Please Help me.

Liu
Guest
Liu

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!

KiranKumar
Guest
KiranKumar

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
kirankumar2434@gmail.com is my mail id.

Marin Kamal
Guest
Marin Kamal

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

sai
Guest
sai

hi ,
how to print the count value in html page

Deep Shah
Guest
Deep Shah

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.

Tommy Paulsen
Guest
Tommy Paulsen

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

Ivan Huang
Guest
Ivan Huang

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!

Deepak
Guest
Deepak

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

trackback
Spring – How to do dependency injection in your session listener | Spring

[…] tutorial will extend this HttpSessionListener example by doing dependency injection a bean into the session […]

guido
Guest
guido

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

kk
Guest
kk

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

Cam
Guest
Cam

How it work?…. “How does it work” :D