Implementing the HttpSessionAttributeListener
will make the servlet container inform you about session attribute changes. The notification is in a form of HttpSessionBindingEvent
object. The getName()
on this object tell the name of the attribute while the getValue()
method tell about the value that was added, replaced or removed.
package org.kodejava.servlet;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
@WebListener
public class SessionAttributeListener implements HttpSessionAttributeListener {
@Override
public void attributeAdded(HttpSessionBindingEvent event) {
// This method is called when an attribute is added to a session.
// The line below display session attribute name and its value.
System.out.println("Session attribute added: ["
+ event.getName() + "] = [" + event.getValue() + "]");
}
@Override
public void attributeRemoved(HttpSessionBindingEvent event) {
// This method is called when an attribute is removed from a session.
System.out.println("Session attribute removed: ["
+ event.getName() + "] = [" + event.getValue() + "]");
}
@Override
public void attributeReplaced(HttpSessionBindingEvent event) {
// This method is invoked when an attribute is replaced in a session.
System.out.println("Session attribute replaced: ["
+ event.getName() + "] = [" + event.getValue() + "]");
}
}
Maven dependencies
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024