Tuesday, August 06, 2013

How to Track Session Attribute - HttpSessionAttributeListener Example

If You want to track session Attribute like whether there is new session attribute added,removed or replaced during application lifecycle then HttpSessionAttributeListener is for You !

HttpSessionAttributeListener is abstract interface which comes as part of servlet-api.jar which has abstract method such as attributeAdded,attributeRemoved,attributeReplaced.

How it works : 
  • When new session attribute is added using set then attributeAdded will be called.
HttpSession session = request.getSession();
session.setAttribute("sessionName","LoginIn");
  • If you try to set attribute value to some different value which is already present then attributeReplaced will be called. ex. session.setAttribute("sessionName","LoggedIn");
  • If you invalidate session using session.invalidate(); then in that case attributeRemoved will be called.

HttpSessionAttributeListener Example :
package com.anuj.session;

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

/**
 * 
 * @author Anuj
 *
 */
public class AppSessionAttributeListener implements HttpSessionAttributeListener {

 @Override
 public void attributeAdded(HttpSessionBindingEvent bindingEvent) {
  String attributeName = bindingEvent.getName();
  Object attributeValue = bindingEvent.getValue();
  System.out.println("Session Attribute added - "+attributeName+":"+attributeValue);
 }

 @Override
 public void attributeRemoved(HttpSessionBindingEvent bindingEvent) {
  String attributeName = bindingEvent.getName();
  Object attributeValue = bindingEvent.getValue();
  System.out.println("Session Attribute removed - "+attributeName+":"+attributeValue);
 }

 @Override
 public void attributeReplaced(HttpSessionBindingEvent bindingEvent) {
  String attributeName = bindingEvent.getName();
  Object attributeValue = bindingEvent.getValue();
  System.out.println("Session Attribute replaced - "+attributeName+":"+attributeValue);
 }
}
Output :
Aug 06, 2013 11:05:52 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-apr-8080"]
Aug 06, 2013 11:05:52 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-apr-8009"]
Aug 06, 2013 11:05:52 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 217 ms
Session Attribute added - sessionName:LoginIn
Session Attribute replaced - sessionName:LoginIn
ServletConfigEmail : ServletConfig@gmail.com
servletContextEmail : ServletContext@gmail.com
Session Attribute removed - sessionName:LoggedIn

Author : Anuj Patel
Blog : http://goldenpackagebyanuj.blogspot.in/

No comments:

Post a Comment