Solved

Java Session Management

Posted on 2011-03-25
11
469 Views
Last Modified: 2012-06-27
hi,
Im looking for Session management using java....

Eg. Im Mr.A
I login from X computer so it shouldnt allow anyone else to login from another computer using my username...
Also if Admin kills my session which im using on X computer i shouldnt be allowed to post anything and logout automatically.


Kindly suggest.
0
Comment
Question by:CCBRONET
  • 5
  • 3
  • 2
  • +1
11 Comments
 
LVL 8

Expert Comment

by:colr__
ID: 35216357
To enable to admin kick-out, limit your access to the session object to soemthing like the following:

public HttpSession getMySession(){
     if (adminHasKickedMeOut){
          sendmMeSomewhere();
     }
     
}

So everywhere you need tio get holdof the session, use this method instead of the standard HttpRequest.getSession();

As for enabluing only one login frmo a username at a time - use a HttpSessionListener. Keep a singleton object that maintains a list of users who are currently logged in. Then when a new user logs in, in the HttpSessionListener - check the logging in user with the list alrerady present in the singleton. If the username already exists, kick the new user out.

With this method you'll need to make sure and maintain the list of logged in users in the singletong, by making sure and removing users once they log out etc.
0
 
LVL 20

Expert Comment

by:Sathish David Kumar N
ID: 35216884
I have lot of question from your question??

Mr.A is login in one pc. why should you disclose user name and password to every one.

As per I know that's not possible to lock once you login because each system will create different session id for same user !!

But you can do with other way !!

Take one extra field in table with the column name say "IsLoggedIn" as bit field and set it to true until the user is logged in. As soon as user logs out set it to false. This need to be done for session expiry time also. As soon as the session expires this field should be set to false automatically using triggers or thru SP call
0
 
LVL 27

Expert Comment

by:rrz
ID: 35217257
colr's idea of using a listener is good. But I would use an application-scoped Hashtable.  This could be created in the init method of a Servlet that is configured to be loaded on start up. The keys of the table could be the usernames and the values being their Sessions.  That way the Admin can have access to a user's session.
Your log-in code could check the table to see if username is already logged-in. Your log-out code or the Admin can invalidate the user's session. In the sessionDestroyed method of the HttpSessionListener, you can remove the username from the table.  
The only problem with this approach is that the user will be locked out if he closes his browser without logging out. He will have to wait until his session times out. Only then will he be able to log-in again.
0
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
LVL 20

Expert Comment

by:Sathish David Kumar N
ID: 35217348
@rrz@871311:
>>>>>>>>The only problem with this approach is that the user will be locked out if he closes his browser without logging out. He will have to wait until his session times out. Only then will he be able to log-in again.

you are right , But again your open time you have option like killing the old session thats the best

eg:

if again that same user login again (think the user close the browser without logout)

that time browser will ask already existing useer deatils . you can logout that time . but we want to get the ideal time .
0
 
LVL 20

Expert Comment

by:Sathish David Kumar N
ID: 35217358
or you can get the IP address !
0
 
LVL 20

Expert Comment

by:Sathish David Kumar N
ID: 35217383
>>>>>>colr's idea of using a listener is good.But I would use an application-scoped Hashtable.  This could be created in the init method of a Servlet that is configured to be loaded on start up. The keys of the table could be the usernames and the values being their Sessions.

sorry if you use in another pc means ur session id will diffrent right then  how you will use that??
0
 
LVL 27

Expert Comment

by:rrz
ID: 35217500
>you are right , But again your open time you have option like killing the old session thats the best  
If the user closes his browser then the Session id is lost on client-side.  
>or you can get the IP address !  
We could use a Filter for that. A listener can't do it.  
>sorry if you use in another pc means ur session id will diffrent right then  how you will use that??
I suggested that we use usernames as keys in the table. The log-in code will check if the table contains username.
0
 
LVL 20

Expert Comment

by:Sathish David Kumar N
ID: 35217636
i didnt understand thats y i ask that question . dont mind!
0
 

Author Comment

by:CCBRONET
ID: 35398609
ny help pls
0
 
LVL 27

Accepted Solution

by:
rrz earned 500 total points
ID: 35404591
I wrote some demonstration code. It just shows the basic functionality. I created usersTable in the listener to make it easier. I use the Servlet 3.0 API annotations. If you are using Servlet 2.5 API or older then you must register the listener in your web app's web.xml file. For this test I used the Date string instead of creating different usernames.
To test, just browse to the JSP and then close your browser. Do that a number of times. You should see the table grow and shrink in size as the  number of sessions are created and destroyed.   This should get you started. If you have any questions, then ask us here.  
package rrz;   
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebListener;
@WebListener
public class TestListener implements HttpSessionListener , Serializable {
  ServletContext application = null;
  public void sessionCreated(HttpSessionEvent event) {
           System.out.println("sessionCreated in TestListener");
           application = event.getSession().getServletContext();
           if(application.getAttribute("usersTable") == null){
                     application.setAttribute("usersTable", new Hashtable());
           }
           Hashtable<String,String> usersTable = (Hashtable)application.getAttribute("usersTable");
           System.out.println("usersTable==" + usersTable);
  }
  public void sessionDestroyed(HttpSessionEvent event) {
      System.out.println("sessionDetroyed in TestListener");
      Hashtable<String,String> usersTable = (Hashtable)application.getAttribute("usersTable");
      String id = event.getSession().getId();
      if(usersTable.containsValue(id)){
            Set<Map.Entry<String,String>> set = usersTable.entrySet();
            for(Map.Entry entry : set){
                 if(entry.getValue().equals(id)){
                      usersTable.remove(entry.getKey());
                      break;
                 }
            }
      }
      System.out.println("usersTable==" + usersTable);
  }
}

Open in new window

The JSP can be
<%@ page import="java.util.*" %>
<%
  session.setMaxInactiveInterval(30);// 30 seconds for testing
  Hashtable usersTable = (Hashtable)application.getAttribute("usersTable");
  usersTable.put(new Date().toString(), session.getId());
%>
UsersTable is <%=usersTable%>

Open in new window

0
 

Author Closing Comment

by:CCBRONET
ID: 35704793
jioujiuj
0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This video teaches viewers about errors in exception handling.

813 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now