Recipe7.3.Monitoring User Logins


Recipe 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--;         }         ctx.setAttribute("numUsers", new Integer(counter));     } }

Like the other servlet listeners, you declare the class as a listener element in your web 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 version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE web-app PUBLIC     "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"     "http://java.sun.com/dtd/web-app_2_3.dtd">      <web-app>   <display-name>Struts Cookbook - Chapter 7 Examples</display-name>      <listener>       <listener-class>com.oreilly.strutsckbk.ch07.UserCounter       </listener-class>   </listener>   ... rest of web.xml

Discussion

The Servlet 2.3 specification added support for various listener types. Attribute listeners allow you to receive event notifications when an object is added, removed, or replaced in the session and application scopes. A class that implements the HttpSessionAttributeListener interface monitors session-scope objects.

The Solution shown in Example 7-3 shows how an attribute listener can track the number of users logged into your application. When an attribute is added to the session under the name "user," a counter objectmaintained in the servlet contextis incremented. Likewise, when the user object is removed from the session, the counter is decremented. The session listener of Recipe 7.2 provided a similar function. However, using an attribute listener gives you finer-grained monitoring.

The HttpSessionAttributeListener specifies three methods: attributeAdded( ), attributeReplaced( ), and attributeRemoved( ). The servlet container calls attributeAdded( ) when an object is added to the session or servlet context under a new name. If an attribute is added using the name of an existing attribute, the attributeReplaced( ) method is called. When an object is removed from the session or servlet context, the container calls attributeRemoved( ). When an HttpSession is invalidated, the servlet container will call the removeAttribute( ) method of any HttpSessionAttributeListeners for each object in the session. This allows you to perform any necessary cleanup on those objects before the session is destroyed.

Objects can be added, replaced, or removed from the HttpSession and ServletContext using the setAttribute( ) and removeAttribute( ) methods. You can manipulate these objects from a JSP page using custom tags like the standard jsp:useBean, Struts' bean:define, and JSTL's c:set.


The session attribute that caused the event is accessible via the HttpSessionBindingEvent object passed to each notification method. The getValue( ) method retrieves the object and the getName( ) retrieves the attribute's name.

See Also

You can monitor attributes added to the ServletContext using a ServletContextAttributeListener. Furthermore, the Servlet 2.4 specification adds a ServletRequestAttributeListener and lets you monitor objects added to any servlet request.

The HttpSessionBindingListener interface allows objects being managed as session attributes to be notified when they're bound or unbound from the session. The methods of this interface are triggered by the same events as the HttpSessionAttributeListener. The JavaDocs for the session binding listener can be found at http://java.sun.com/products/servlet/2.3/javadoc/javax/servlet/http/HttpSessionBindingListener.html.

If you are unfamiliar with servlet programming, you should check out Java Servlet Programming by Jason Hunter (O'Reilly). This classic work will give you all the information you need to create highly functional servlets and servlet-related classes.



    Jakarta Struts Cookbook
    Jakarta Struts Cookbook
    ISBN: 059600771X
    EAN: 2147483647
    Year: 2005
    Pages: 200

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net