How to Calculate Total Active Session - HttpSessionListener Example

If you have web application and you want to count total number of active session then HttpSessionListener is for you !

HttpSessionListener is abstract interface provided as part of servlet-api.jar which has abstract method such as sessionCreated and sessionDestroyed which get executed every time when we create new session using httpSession or invalidate session.

By default one session is created. so when you use HttpSession session = request.getSession(); in HttpServlet then it will give you that session. You can invalidate session using session.invalidate();


HttpSessionListener Example :

package com.anuj.session;

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

/**
 * 
 * @author Anuj
 *
 */
public class AppSessionListener implements HttpSessionListener{

 private static int totalNoOfActiveSession;
 
 public static int getTotalActiveSession() {
  return totalNoOfActiveSession;
 }

 @Override
 public void sessionCreated(HttpSessionEvent event) {
  System.out.println("New Session Created");
  totalNoOfActiveSession++;
  System.out.println("Total no of active session - "+getTotalActiveSession());
 }

 @Override
 public void sessionDestroyed(HttpSessionEvent event) {
  System.out.println("Existing Session Destroyed");
  totalNoOfActiveSession--;
  System.out.println("Total no of active session - "+getTotalActiveSession());
 }
}
Defining SessionListener in web.xml deployment descriptor :

    com.anuj.session.AppSessionListener


Output :

Aug 06, 2013 10:46:53 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 209 ms
New Session Created
Total no of active session - 1
Existing Session Destroyed
Total no of active session - 0

No comments:

Post a Comment