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.3. Monitoring User Logins

Problem

You want to know when a user has logged into your application.

Solution

Create a class that implements the HttpSessionAttributeListener for session-scoped objects. The class shown in Example 7-3 tracks the number of logged-in users of an application by listening for the addition and removal of a User object to or from the session.

Example 7-3. Session attribute listener

package com.oreilly.strutsckbk.ch07;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

public class UserCounter implements HttpSessionAttributeListener { public void attributeAdded(HttpSessionBindingEvent event) { if (attributeIsUser(event)) adjustUserCounter(event.getSession( ).getServletContext( ), true); } public void attributeRemoved(HttpSessionBindingEvent event) { if (attributeIsUser(event)) adjustUserCounter(event.getSession( ).getServletContext( ), false); } public void attributeReplaced(HttpSessionBindingEvent event) { } private boolean attributeIsUser(HttpSessionBindingEvent event) { String name = event.getName( ); Object value = event.getValue( ); return "user".equals(name) && value instanceof com.oreilly.strutsckbk.ch07.User; } private void adjustUserCounter(ServletContext ctx, boolean userAdded) { Integer counterObj = (Integer) ctx.getAttribute("numUsers"); int counter = (counterObj == null ? 0 : counterObj.intValue( )); if (userAdded) { counter++; } else { if (counter > 0) counter--; ...
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