HttpSessionBindingListener Example Use Case
This example explains how to use a HttpSessionBindingListener
in a web application. This interface must be placed on an Object. It causes the Object to be notified when it is bound or unbound from an HttpSession. The events are invoked when session.setAttribute()
or session.removeAttribute()
or session.invalidate()
is used.
HttpSessionBindingListener receives notifications for HttpSession attribute changes
In order to listen when an Object is added to the session, the Object must implement the javax.servlet.HttpSessionBindingListener
interface. This interface lets us listen to the following events.
valueBound()
: this method is called when the Object is bound to the HttpSession. More specificaly when thesession.setAttribute()
is invoked.valueUnbound()
: this method is called when the Object is unbound from the HttpSession. When thesession.removeAttribute()
orsession.invalidate()
methods are invoked.
package com.memorynotfound;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
public class User implements HttpSessionBindingListener {
private String name;
public User(String name) {
this.name = name;
}
@Override
public void valueBound(HttpSessionBindingEvent event) {
User user = (User)event.getValue();
System.out.println("New user bound in session with name: " + user.getName());
}
@Override
public void valueUnbound(HttpSessionBindingEvent event) {
User user = (User)event.getValue();
System.out.println("User with name: " + user.getName() + " removed from session");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
How does it work
We defined our listener to the User Class. Every time when the User Object is added to the session via session.setAttribute()
the valueBound()
method is invoked for that specific object. And the valueUnbound()
is invoked every time a User Object is removed from the session either via session.removeAttribute()
or session.invalidate()
.