skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Wednesday, October 17, 2012

Prevent Concurrent Logins from the Same UserID

Posted by Raju Gupta at 6:00 PM – 0 comments
 

This code snippet mainly addresses the problem of Implementation to avoid Concurrent Logins from the Same User ID in Java. This is implemented by using the Concept of Session Listeners in Java. Whenever a Session Event takes place(i.e., either a session is created or Destroyed) for a particular user, then this Session Listeners Class will be called and we can override the functions of it, so as to address our requirements.   

import java.util.HashMap;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
 
public class SessionListener implements HttpSessionListener {
   
    private int sessionCount = 0;
    
    public void sessionCreated(HttpSessionEvent event) {
		
        synchronized (this) {
            sessionCount++;
        }

        
        System.out.println("Session Created: " + event.getSession().getId());
        System.out.println("Total Sessions: " + sessionCount);
    }
 
    public void sessionDestroyed(HttpSessionEvent event) {
        synchronized (this) {
            sessionCount--;
        }
        
/* hMap is a HashMap that is maintained in the ServletContext, which makes it available throughout the Application. In that, Session ID and UserName is stored whenever a new user is logged in. And if a new user tries to login, we shall check if the username is present in the HashMap, if No, he will be authenticated else, we shall redirect him to login page. */

        System.out.println("Session Destroyed: " + event.getSession().getId());
        try{
        	
        	HashMap hMap=(HashMap) event.getSession().getServletContext().getAttribute("hMap");
        	System.out.println("hMap::"+hMap);
        	event.getSession().getServletContext().removeAttribute((String) hMap.remove(event.getSession().getId()));
        	System.out.println("hMap after removing::"+hMap);
        }
        catch(Exception e){
        	e.printStackTrace();
        }
        System.out.println("Total Sessions: " + sessionCount);
    }
}

/* Copy this Snippet in Web.xml in your Application as well. */



     
        ( .<)
    



Leave a Reply

Newer Post Older Post
Subscribe to: Post Comments ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger