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

Get Jakarta Struts Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.