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 :
Founder of Mkyong.com, love Java and open source stuffs. Follow him on Twitter, or befriend him on Facebook or Google Plus.
Here are some of my recommended Books

Related Posts

Popular Posts