Tuesday, 27 January 2015

Multiple servlet sessions - invalidate another servlet

What happens when a user logins multiple times? There will be two different sessions. This information is on how to identify multiple login sessions by same user and invalidate the addtional another session. Following code snippet details the usage:
 


import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;



public class SessionBindingListenerExample implements  HttpSessionBindingListener {

    private String userID;

    private static Map<String, HttpSession> logins =

    new HashMap<String, HttpSession>();

    public SessionBindingListenerExample () {}

   
    public void valueBound(HttpSessionBindingEvent event) {
     System.out.println("VALUE BOUND.");

     try{
  
     HttpSession session = event.getSession();
     HttpSession existingSession = (logins.get(userID) != null) ?

     logins.remove(userID) : null;
   

     if(existingSession != null) existingSession.invalidate();
 
     logins.put(userID,session);
   
 
     }catch(Exception e){
        e.printStackTrace();
     }  

    }

    public void valueUnbound(HttpSessionBindingEvent event) {
       System.out.println("VALUE UNBOUND.");
    }


    public String getUserID(){
       return userID;
    }

 
    public void setUserID(String userID){
       this.userID =  userID;
    }
}


Call the above class from the servlet as follows:

  String user = request.getParameter("user");
  SessionBindingListenerExample myuser  =

  new SessionBindingListenerExample ();
  myuser.setUserID(user);
      
  request.getSession().setAttribute("username",myuser);