Solved

Java Session Management

Posted on 2011-03-25
11
463 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__
Comment Utility
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
Comment Utility
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
Comment Utility
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
 
LVL 20

Expert Comment

by:Sathish David Kumar N
Comment Utility
@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
Comment Utility
or you can get the IP address !
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 20

Expert Comment

by:Sathish David Kumar N
Comment Utility
>>>>>>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
Comment Utility
>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
Comment Utility
i didnt understand thats y i ask that question . dont mind!
0
 

Author Comment

by:CCBRONET
Comment Utility
ny help pls
0
 
LVL 27

Accepted Solution

by:
rrz earned 500 total points
Comment Utility
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
Comment Utility
jioujiuj
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Suggested Solutions

I had a project requirement for a displaying a user workbench .This workbench would consist multiple data grids .In each grid the user will be able to see a large number of data. These data grids should allow the user to 1. Sort 2. Export the …
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

743 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