File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Servlets and the fly likes remove all user Sessions Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "remove all user Sessions" Watch "remove all user Sessions" New topic
Author

remove all user Sessions

Saritha Penumudi
Ranch Hand

Joined: Aug 18, 2003
Posts: 147
Hi,
I am not sure if this is the right place to post my query. If I have to post this in JSP forum or Servlet forum.

I am working on a web application which uses Jsp, Struts, EJB and oracle DB.

I have a functionality where Administrator should be able to view all the users sessions who have logged into the system and logoff them if required. In this case he should be able remove all user sessions.

How administrator will be able to get access to all the user session objects which are creacted when use has logged into the system?.

Any other procedure or methodology to acheive this would be appreciated.

This is kind of an urgent. early replys would be appreciated

Thank you very much
Saritha
Jessica Sant
Sheriff

Joined: Oct 17, 2001
Posts: 4313

ooo I don't think you can do that in a web application. Which app server are you using? maybe they have some utility that lets you do that?


- Jess
Blog:KnitClimbJava | Twitter: jsant | Ravelry: wingedsheep
Saritha Penumudi
Ranch Hand

Joined: Aug 18, 2003
Posts: 147
We are using Oracle 10g application server.
Rovas Kram
Ranch Hand

Joined: Aug 08, 2003
Posts: 135
javax.servlet.http.HttpSessionContext used to be used for this but it's now been deprecated for security reasons. I'm not sure why because an application developer can still store all the sessions in a global HashMap.
Saritha Penumudi
Ranch Hand

Joined: Aug 18, 2003
Posts: 147
Yes,
I did go through HttpSessionContext and I cannot use it now.

Do you suggest me to declare a hashmap and add it to the servlet context (application scope) and use that to hold my Hashmap?

Hashmap would contain userId and session objects. When user session timeout or when he logges out of the system or when administrator kicks him out remove session objects from the hashmap.

Session object also holds user Menu items which is used to build menu at runtime, and some information which is specific to user.

Do you think there will be any performance issues with this approach.

Thank you
Saritha
Peter den Haan
author
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
Use a HttpSessionListener, rather than a homegrown mechanism, to detect when sessions are created and destroyed. The listener can keep track of them in an application scoped map or other data structure, as you indicate.

To kick a user out, simply invalidate() the session. That's all. The container will call the listener, and your listener implementation will remove the session from its map as normal.

There are no a priori performance issues. You better be well versed in concurrent programming though, or hire a consultant who is.

- Peter
[ September 02, 2004: Message edited by: Peter den Haan ]
Saritha Penumudi
Ranch Hand

Joined: Aug 18, 2003
Posts: 147
Thank you very much for your reply.

I tried to implement ur suggestion. I was getting following errors.

I am using Oracle 10g application server. I guess it supports j2ee1.3 and I have seen that servlet specification in j2ee1.3 should support HttpSessionListener.

This is my servlet class.
------------------
package demo.servlets;

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

import demo.utility.Constants;
import com.utilities.logging.MyLogger;
import com.utilities.logging.LoggingFactory;

public class ManageSessions extends HttpServlet implements HttpSessionListener {

HashMap userSessions = null;
//MyLogger logger = null;
public void init(ServletConfig config) throws ServletException{
userSessions = new HashMap();
(config.getServletContext()).setAttribute("userSessions",userSessions);

System.out.println("In Servlet Init");
}
//Notification that a session was created
public void sessionCreated(HttpSessionEvent se) {

if(userSessions == null)
userSessions = new HashMap();

String userName =
((demo.vo.UserVO)((se.getSession()).getAttribute(Constants.USERKEY))).getUserName();
/*
if(logger == null)
logger = LoggingFactory.getLogger(this,"safari");
logger.debug("User "+userName+" has logged into the system");
*/

userSessions.put(userName,se.getSession());
System.out.println("In Session Created User Hashmap:"+userSessions);
}

//Notification that a session was invalidated
public void sessionDestroyed(HttpSessionEvent se) {
String userName =
((demo.vo.UserVO)((se.getSession()).getAttribute(Constants.USERKEY))).getUserName();
/*
if(logger == null)
logger = LoggingFactory.getLogger(this,"safari");
logger.debug("User "+userName+" has logged out of the system");
*/

if(userSessions != null){
userSessions.remove( (se.getSession()).getAttribute(Constants.USERKEY));
}
System.out.println("In Session Removed User Hashmap:"+userSessions);
}
}
------------------

In the program, I am trying to hold sessions in a Hashmap and remove sessions from the Hashmap on session inactivate/expire/logout.

I initially thought of initializing all my variables in init method. I am not sure if init is being called. Hence I had to initialize in sessionCreated and sessionDestroyed methods. In my web.xml file I added following entries.
-----------------
<listener>
<listener-class>demo.servlets.ManageSessions</listener-class>
</listener>
-----------------

when I deploy my application in the Application server, I am able to see the println statements from sessionDestroyed but not from sessionCreated.
In my LogonAction.java class, I am creating session using request.getSession(); method. I guess it should generate sessionCreatedEvent.

Please help me out in solving this problem. I have been working on this since this afternoon and I am now like .

I will really approciate if you provide some documentation on this concept
Thank you very much inadvance. early replys would be greatly appreciated.

Thank you
Saritha
[ September 13, 2004: Message edited by: Saritha ventrapragada ]
Sekhar Kadiyala
Ranch Hand

Joined: Feb 17, 2004
Posts: 170
First of all, to my knowledge, se.getSession()).getAttribute call is not valid in sessionDestroyed method.

By the time, sessionDestroyed method is called, all the session attributes would have been invalidated.


PMP CSQA SCJP SCWCD SCBCD INS 21 INS 23
Saritha Penumudi
Ranch Hand

Joined: Aug 18, 2003
Posts: 147
Thank you for your response.
But, I am able to get the user Name from the session by making this call
se.getSession()).getAttribute.

why sessionCreated method is not being called. When will that event get generated?
Sekhar Kadiyala
Ranch Hand

Joined: Feb 17, 2004
Posts: 170
Good News!
I tried this exercise and was able to destroy all the sessions programmatically..

If you would like to take a look, i will send you the code, that i worked with. Pls send me your email id

miru telugu ammaya!?

sessionCreated should get instatiated as soon as you load a JSP (if that does have the statement
[B] <%@ page session"false" %>

I am not sure, why it is not displaying the message.

Let me again go thru your implementation class
Saritha Penumudi
Ranch Hand

Joined: Aug 18, 2003
Posts: 147
Hi,

Thank you very much. I would really appreciate if you could send me your code. This is my email address. vsaritha_9@yahoo.com.

avunu nenu telugu ammayine.

I did not had <@page session='false'> tag in my jsp page, But I was creating new session in my struts Action class by saying request.getSession()

I really appreciate your reply
Thank you
Saritha
Sekhar Kadiyala
Ranch Hand

Joined: Feb 17, 2004
Posts: 170
Looking at this code, why do you want to extend HttpServlet?
May be for init method? Would it be possible for you to create that HashMap object elsewhere and not in this class?

Also whenever you override init(ServletConfig) method, you must include a call to super.init(ServletConfig). Usually its better to override init() method only. Notice that there is no argument.

SessionDestroyed is working means, sessions are getting created.

May be for verification sake, you may want to remove extending HttpServlet and just see
Sekhar Kadiyala
Ranch Hand

Joined: Feb 17, 2004
Posts: 170
What i meant was session should get created as soon as a JSP is loaded
if it doesn't have the statement

<%@ page session="false" %>

by default every JSP participates in a session
Sekhar Kadiyala
Ranch Hand

Joined: Feb 17, 2004
Posts: 170
I have sent the sample code to your email. Let me know, if you have received it.

Regards,
Sekhar
Saritha Penumudi
Ranch Hand

Joined: Aug 18, 2003
Posts: 147
Hi Shekar,

I did not get your email yet. This is my email id vsaritha_9@yahoo.com. Just to make sure that you have correct one.

I really appreciate all your help

Thank you very much
Saritha
Sekhar Kadiyala
Ranch Hand

Joined: Feb 17, 2004
Posts: 170
I have sent it to the same ID. This time i have sent it from my Yahoo id. Please verify
Saritha Penumudi
Ranch Hand

Joined: Aug 18, 2003
Posts: 147
Thank you very much.
I got your code.

I have one more question.

sessionCreated method is being called before I create session in my LogonAction class using request.getSession(). In Logon.jsp I have included this directive <%@ page session="false" %> so that session will not be created. sessionCreated event is not generated when I create one by calling request.getSession() method.

I am not clear how all this works. Can u please provide me some links abt this concept.

Thank you
Saritha
Sekhar Kadiyala
Ranch Hand

Joined: Feb 17, 2004
Posts: 170
okay here is the deal.
request.getSession() doesn't create a session. It just retrieves an already created session.

When the servlet container tries to load the page logon.jsp, it will look for the session attribute in the page directive (<%@ page session="true" %>). If it not present or if it present with the value "true", it creats the session. This is the time when session is created.

Please note that by default every JSP page participates in session.
if you do not want it, you must explicitly mention <%@ page session="false" %>

since you have mentioned that statement session was not created when logon.jsp was loaded. so sessionCreated event didn't fire.

Hope this helps. If you still have questions, pls fire!
Saritha Penumudi
Ranch Hand

Joined: Aug 18, 2003
Posts: 147
First of all thank you for being very patience with me.

Here are my questions:

1. As per your explanation, Session Created should not get fired when I include <%@ page session="false" %> in my logon.jsp. But this event is being fired.

2. Yes, request.getSession() would return session if one has aleardy been created. If not, then it would create one. Hence I have used this method instead of request.getSession(true) method. Even though sessionCreated event is not being fired.

I have implemented ServletContextListener and created HashMap in contextInitialized method. In my LogonAction, upon successful login, I am creating session by calling request.getSession() method. Getting Hashmap from the ServletContext, Added my session to the hashmap.
As sessionDestroyed event is being fired on invalidate, I am removing session from Hashmap in sessionDestroy method upon logout.

I would apprecite if you let me know if there are any pitfalls with this approach.

I really appreciate all your help. Thank you very much
Saritha
[ September 15, 2004: Message edited by: Saritha ventrapragada ]
Sekhar Kadiyala
Ranch Hand

Joined: Feb 17, 2004
Posts: 170
I guess this approach should work. To my knowledge, i don't see issues with this approach.

Few clarifications

1. As per your explanation, Session Created should get fired when I include <%@ page session="false" %> in my logon.jsp. But this event is being fired.


No session won't get fired, as you have specified session as false. Session would be created only if it was session="true".
Neverthless, since you are creating the session thru request.getSession(), this should be okay. But please do not specify session="false" in the logon.jsp, unless you have any valid reson.

I am assuming you would provide another page to your Admin, to invalidate the user sessions (one by one or all at once). In that page please make sure you are handling exceptions throughly. As at times, DBA might keep that page open for few minutes and in between some user sessions might get timeed-out or would have got invalidated for some other reason, in such case, if you don't handle them properly, your Admin would end up with a big stack trace!!

Also, it is not advisable to retrieve any attributes from session object in sessionDestroyed method. specs never guarantee you that information would be available in session object of the sessionDestroyed method. So though it might work for you now, but if you migrate that code to some other server or a newer version, you might face issues with that.

Otherwise the approach you are following should work without any trouble!

Good Luck,
Sekhar
Saritha Penumudi
Ranch Hand

Joined: Aug 18, 2003
Posts: 147
Thank you Sekhar,

That was a typo in my message. I have corrected that mistake.
If it is not good approach to get values form the session in the sessionDestroyed method, then I don't think there is any other way I can remove session objects from my Hashmap on session expiry.

Thank you for letting me know abt all such scenarios.
Saritha
Sekhar Kadiyala
Ranch Hand

Joined: Feb 17, 2004
Posts: 170
No. You can even remove the values from valueUnbound method of HttpSessionBinindListener listener clas.

To do this, you have to implement this listener on your user class and in the valueUnbound method, you can remove that particular user (which is getting removed from session) from HaspMap.

Alternatively, wouldn't be okay to delete it from HashMap when u r calling invalidate method?
 
Don't get me started about those stupid light bulbs.
 
subject: remove all user Sessions
 
Similar Threads
special characters
How should i keep user info after successful login?
Java socket connection does not work in Vista
How to ge know which users are using an app?
Authenticator issue