HttpSessionAttributeListener Example

HttpSessionAttributeListener Example explains about how to use HttpSessionAttributeListener in a web application.

HttpSessionAttributeListener is an interface which is extending from the base interface java.util.EventListener. HttpSessionAttributeListener will be informed by the web container when there is a change to the attributes of a web application's session, like an attribute is added in a session or an attribute is removed or an attribute is replaced by another attribute etc.

HttpSessionAttributeListener interface has following methods:

attributeAdded(HttpSessionBindingEvent event)
attributeRemoved(HttpSessionBindingEvent event)
attributeReplaced(HttpSessionBindingEvent event)

Example Package Structure

HttpSessionAttributeListener Example

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    version="2.5">
    <listener>
        <listener-class>com.listener.HttpSessionAttributeListenerExample</listener-class>
    </listener>
</web-app>

HttpSessionAttributeListenerExample.java

package com.listener;

import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

public class HttpSessionAttributeListenerExample 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);
 
}
}

Servlet Usage

HttpSession session = request.getSession();
//When new session attribute is created then attributeAdded() is executed
session.setAttribute("url", "javatips.net");
//When session attribute is replaced then attributeReplaced() is executed
session.setAttribute("url", "javatips.net");
//When session attribute removed then attributeRemoved() is executed
session.removeAttribute("url");
1 2 Next





Your email address will not be published. Required fields are marked *