O'Reilly logo

Jakarta Struts Cookbook by Bill Siggelkow

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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--; ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required