Counting the Number of Sessions
Written by Joseph Ottinger
Counting the number of sessions is fairly easy.
In the servlet specification, there's a concept of a "session listener," which provides callback points for session creation and session destruction.
Therefore, to count sessions, one would simply create a session listener that had an access method to either a count of active sessions, and install it in a given web application (via web.xml).
Such a listener might look like this:
import javax.servlet.http.*;
public class OSSessionListener implements HttpSessionListener {
public static int sessionCount=0;
void sessionCreated(HttpSessionEvent event) {
sessionCount++;
}
void sessionCreated(HttpSessionEvent event) {
sessionCount--;
}
}
Then, to view the number of sessions active in, say, a JSP page, one would simply have a snippet such as:
<%= OSSessionListener.sessionCount %>
If finer-grained access is needed, the listener could store a map of the sessions and get the size of the map's key set, but note that providing access to this map might have some negative security implications.
Copyright © 2007 IronFlare AB