Session Listener

Created: 31.07.2014

HTTPSessionBindingListener for SessionScoped ManagedBeans

If you want to listen for the creation or deletion of certain session scoped beans, you can implement the interface HTTPSessionBindingListener in the corresponding @ManagedBean. There is no need to register such a listener in your web.xml.

Imagine, for instance, a LoginHandler that manages a user session and the authenticated user as an object.

@ManagedBean
@SessionScoped
public class LoginHandler {
	private User currentUser;

	public User getCurrentUser() {
		return currentUser;
	}

	public String login() {
		//check for authentication
		currentUser = authenticatedUserFromDatabase;
		return "/Welcome.xhtml";
	}
}

If an authenticated user quits his session by closing the browser, you might want to take some actions. You can achieve this by implementing HTTPSessionBindingListener.

@ManagedBean
@SessionScoped
public class LoginHandler implements HttpSessionBindingListener{
    @Override
    public void valueBound(HttpSessionBindingEvent event) {
        //..
    }

    @Override
    public void valueUnbound(HttpSessionBindingEvent event) {
        if(this.currentUser != null){
            //do somethig with that user
        }
    }
}