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.

About the Author

author image
mkyong
Founder of Mkyong.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

Leave a Reply

avatar
newest oldest most voted
Mac User
Guest
Mac User

Thanks a ton !!!

skan
Guest
skan

thanks!!!~~

hai nam
Guest
hai nam

thanks sir !

Pavan
Guest
Pavan

Hi

could you explain how to you handle exceptions in

valueUnbound(HttpSessionBindingEvent arg0)

vas
Guest
vas

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

padmanaban
Guest
padmanaban

thanks a lot….

Levan
Guest
Levan

What can I say, thanks again )

robin foe
Guest
robin foe

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