February 2005
Intermediate to advanced
528 pages
12h 53m
English
You need to keep track of the number of clients currently using your application.
Create a class that implements the
HttpSessionListener
interface, like the one shown in Example 7-2, that
keeps count of the total number of active sessions.
Example 7-2. Session-counting listener
package com.oreilly.strutsckbk.ch07;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class SessionCounter implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent event) {
ServletContext ctx = event.getSession( ).getServletContext( );
Integer numSessions = (Integer) ctx.getAttribute("numSessions");
if (numSessions == null) {
numSessions = new Integer(1);
}
else {
int count = numSessions.intValue( );
numSessions = new Integer(count + 1);
}
ctx.setAttribute("numSessions", numSessions);
}
public void sessionDestroyed(HttpSessionEvent event) {
ServletContext ctx = event.getSession( ).getServletContext( );
Integer numSessions = (Integer) ctx.getAttribute("numSessions");
if (numSessions == null) {
numSessions = new Integer(0);
}
else {
int count = numSessions.intValue( );
numSessions = new Integer(count - 1);
}
ctx.setAttribute("numSessions", numSessions);
}
}Declare your class in a listener element of your
application's
web.xml
file. The listener element is supported by Version
2.3 or 2.4 of the Servlet specification—the DTD must specify
Version 2.3 or 2.4:
<?xml ...