A simple HttpSessionAttributeListener example

Here’s a simple “HttpSessionAttributeListener” example to keep track session’s attribute in a web application. If you want to keep monitor your session’s attribute add , update and remove behavior, then consider this listener.

Java Source

package com.mkyong;
 
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
 
public class MyAttributeListener implements HttpSessionAttributeListener {
 
	@Override
	public void attributeAdded(HttpSessionBindingEvent event) {
		String attributeName = event.getName();
		Object attributeValue = event.getValue();
		System.out.println("Attribute added : " + attributeName + " : " + attributeValue);
	}
 
	@Override
	public void attributeRemoved(HttpSessionBindingEvent event) {
		String attributeName = event.getName();
		Object attributeValue = event.getValue();
		System.out.println("Attribute removed : " + attributeName + " : " + attributeValue);
	}
 
	@Override
	public void attributeReplaced(HttpSessionBindingEvent event) {
		String attributeName = event.getName();
		Object attributeValue = event.getValue();
		System.out.println("Attribute replaced : " + attributeName + " : " + attributeValue);	
	}
}

web.xml

<web-app ...>
        <listener>
		<listener-class>com.mkyong.MyAttributeListener</listener-class>
	</listener>
</web-app>

How it work?

– If a new session’s attribute is added, the listener’s attributeAdded() will be executed.
– If a new session’s attribute is updated, the listener’s attributeReplaced() will be executed.
– If a new session’s attribute is removed, the listener’s attributeRemoved() will be executed.

  HttpSession session = request.getSession();
  session.setAttribute("url", "mkyong.com"); //attributeAdded() is executed
  session.setAttribute("url", "mkyong2.com"); //attributeReplaced() is executed
  session.removeAttribute("url"); //attributeRemoved() is executed

All the methods are accept a “HttpSessionBindingEvent” as argument, so you can get the name and value of the attribute that triggered this event.

Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

  • hai nam

    thanks sir !

  • Pavan

    Hi

    could you explain how to you handle exceptions in

    valueUnbound(HttpSessionBindingEvent arg0)

  • vas

    i need to get HttpServletRequest obj in the attributeXXX() is it possible or not

  • padmanaban

    thanks a lot….

  • Levan

    What can I say, thanks again )

  • robin foe

    Yoooong.. hahhaha remember me??
    thx for the tips.. hahahahha

    • http://www.mkyong.com mkyong

      hi robin, of course i do ~ hehe