Skip to Main Content
Jakarta Struts Cookbook
book

Jakarta Struts Cookbook

by Bill Siggelkow
February 2005
Intermediate to advanced content levelIntermediate to advanced
528 pages
12h 53m
English
O'Reilly Media, Inc.
Content preview from Jakarta Struts Cookbook

7.2. Tracking Client Sessions

Problem

You need to keep track of the number of clients currently using your application.

Solution

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming Jakarta Struts

Programming Jakarta Struts

Chuck Cavaness
Beginning Spring Framework 2

Beginning Spring Framework 2

Bruce Snyder, Sing Li, Anne Horton, Thomas Van de Velde, Naveen Balani, Christian Dupuis
Java Cookbook

Java Cookbook

Ian F. Darwin
Struts 2 in Action

Struts 2 in Action

J. Scott Stanlick, Chad Michael Davis, Donald J. Brown

Publisher Resources

ISBN: 059600771XSupplemental ContentErrata Page