Main Tutorials

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 Author

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

Comments

Subscribe
Notify of
20 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
jeevan
6 years ago

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

Cam
7 years ago

How it work?…. “How does it work” 😀

François-Xavier Robin
11 years ago

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.

Adrian
6 years ago

well done !!

Zephyrv
7 years ago

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.

Rafiqul Islam
10 years ago

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

30

Please Help me.

KiranKumar
11 years ago

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.

Marin Kamal
11 years ago

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
11 years ago

hi ,
how to print the count value in html page

Deep Shah
11 years ago

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.

rabah
4 years ago
Reply to  Deep Shah

yeah !!! tell us how to Filter please

Tommy Paulsen
8 years ago
Reply to  Deep Shah

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
7 years ago
Reply to  Tommy Paulsen

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
11 years ago

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

guido
14 years ago

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

venkat
9 years ago
Reply to  mkyong

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

kk
14 years ago

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

Asif
9 years ago

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

Liu
10 years ago

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!