Sunday, 24 April 2016

How to do some task when data is added or removed from the session when user login or logout ?


Scenario 1
I have an attribute class
Class User{
  String name;
  String address;
  String phoneNo;
  boolean isLogged;
}

This class will be added to the session when user logs in and removed from the session when user logs out.
I want its isLogged flag to be changed when user login and logs out.
Using which listener I can do it ?

Solution
Use listener "javax.servlet.http.HttpSessionBindingListener"
It causes an object to be notified when it is bound to or unbound from a session.
The object is notified by an HttpSessionBindingEvent object.

Method Summary
void valueBound(HttpSessionBindingEvent event)
          Notifies the object that it is being bound to a session and identifies the session.
void valueUnbound(HttpSessionBindingEvent event)
          Notifies the object that it is being unbound from a session and identifies the session.


Scenario 2
A class implements HttpSessionBindingListener and an object of that class is in session.
If you invalidate the session, which method of that class will be invoked ?

Solution
When a session is invalidated, all the session attributes are unbound from the session.
If any attribute implements HttpSessionBindingListener, the valueUnbound() method will be called on the attribute.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.