Main Tutorials

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 Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
9 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Mac User
7 years ago

Thanks a ton !!!

skan
9 years ago

thanks!!!~~

hai nam
10 years ago

thanks sir !

Pavan
10 years ago

Hi

could you explain how to you handle exceptions in

valueUnbound(HttpSessionBindingEvent arg0)

vas
10 years ago

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

padmanaban
11 years ago

thanks a lot….

Levan
11 years ago

What can I say, thanks again )

robin foe
14 years ago

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