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.
Thanks a ton !!!
thanks!!!~~
thanks sir !
Hi
could you explain how to you handle exceptions in
valueUnbound(HttpSessionBindingEvent arg0)
i need to get HttpServletRequest obj in the attributeXXX() is it possible or not
thanks a lot….
What can I say, thanks again )
Yoooong.. hahhaha remember me??
thx for the tips.. hahahahha
hi robin, of course i do ~ hehe