4 of Volume 1).
Third, we chose an extremely low session timeout: two minutes. This saved us
from waiting for hours to test the session-counting listener. Changing the default session
timeout is discussed in Section 2.11 (Controlling Session Timeouts), but it simply
amounts to creating a session-config entry in web.xml, as follows:
2
Chapter 6 ?– The Application Events Framework 300
Listing 6.19 SessionCounter.java
package coreservlets.listeners;
import javax.servlet.*;
import javax.servlet.http.*;
/** Listener that keeps track of the number of sessions
* that the Web application is currently using and has
* ever used in its life cycle.
*/
public class SessionCounter implements HttpSessionListener {
private int totalSessionCount = 0;
private int currentSessionCount = 0;
private int maxSessionCount = 0;
private ServletContext context = null;
public void sessionCreated(HttpSessionEvent event) {
totalSessionCount++;
currentSessionCount++;
if (currentSessionCount > maxSessionCount) {
maxSessionCount = currentSessionCount;
}
if (context == null) {
storeInServletContext(event);
}
}
public void sessionDestroyed(HttpSessionEvent event) {
currentSessionCount--;
}
/** The total number of sessions created. */
public int getTotalSessionCount() {
return(totalSessionCount);
}
/** The number of sessions currently in memory.
Pages:
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353