A simple HttpSessionListener example – active sessions counter
Written on December 5, 2009 at 5:38 am by
mkyong
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
This article was posted in Servlet category.
All Java Tutorials
- Java Core Technology - Java RegEx, Java XML, Java I/O, Java Misc
- J2EE Frameworks - Hibernate, Spring 2.5, Spring MVC, Struts 1.x, Struts 2.x
- Build Tools - Maven, Archiva
- Unit Test - jUnit, TestNG
- Client Scripts - jQuery
[...] tutorial will extend this HttpSessionListener example by doing dependency injection a bean into the session [...]
Do you know how to integrate it with Spring ? I mean, how to use dependency injection in your session listener. Thanks.
See this example, http://www.mkyong.com/spring/spring-how-to-do-dependency-injection-in-your-session-listener/
you need to use ContextLoaderListener for the integration.
You have a concurrency problem in the listener, consider using java.util.concurrent.atomic.AtomicInteger instead of int.