FAQ

Java

JSP

Servlet


Advertisement



How to count active sessions in your web application?

If you have unique users on a Web site and need to know who they are or need to get specific information to them, such as search results, then you should be using sessions. A session is a sort of temporary unique connection between the server and client by which the server keeps track of that specific user. That unique session can be used by web applications to display this content to one user and that content to the other user.

How to count active sessions in your web application? For a servlet container or application server which supports Serlvet 2.3 speicification, we can have our session count class implementing HttpSessionListener interface. Our listener object will be called every time a session is created or destroyed by the server. You can find more information about HttpSessionListener at When do I use HttpSessionListener?.

For example, we have MySessionCounter.java that implements HttpSessionListener interface. We implement sessionCreated() and sessionDestroyed() methods, the sessionCreated() method will be called by the server every time a session is created and the sessionDestroyed() method will be called every time a session is invalidated or destroyed.

package com.xyzws.web.utils;

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

public class MySessionCounter implements HttpSessionListener {

private static int activeSessions = 0;

public void sessionCreated(HttpSessionEvent se) {
activeSessions++;
}

public void sessionDestroyed(HttpSessionEvent se) {
if(activeSessions > 0)
activeSessions--;
}

public static int getActiveSessions() {
return activeSessions;
}

}

Compile this code and drop the class file in the /WEB-INF/classes/com/xyzws/web/utils/ folder of your web application.

To receive notification events, the implementation class MySessionCounter must be configured in the deployment descriptor for the web application. add <listener> section into your /WEB-INF/web.xml file:

  <!-- Listeners -->
<listener>
<listener-class>com.xyzws.web.utils.MySessionCounter</listener-class>
</listener>

For example, the following JSP code shows the total active session:

<%@ page import="com.xyzws.utils.MySessionCounter"%>
<html>
...
Active Sessions : <%= MySessionCounter.getActiveSessions() %>
...
</html>


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |