This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Soft Skills and have John Sonmez on-line!
See this thread for details.
The moose likes Servlets and the fly likes Checking for Session Timeout Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "Checking for Session Timeout" Watch "Checking for Session Timeout" New topic
Author

Checking for Session Timeout

Steve Dyke
Ranch Hand

Joined: Nov 16, 2004
Posts: 1488
    
    1
I am trying to figure out how to know when my application timesout so the user can be notified and routed back to logon page. Right now I have the following code in every Servlet but I don't know if this is correct. Is there a way to have a global session object and reference that in the rest of the app?

Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61753
    
  67

Two things:

1) Your test is poor. Put a scoped variable into the session and test for that. When a session expires, the scoped variable will be gone.

2) Use a servlet filter to avoid polluting every servlet with the test.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Steve Dyke
Ranch Hand

Joined: Nov 16, 2004
Posts: 1488
    
    1
Bear Bibeault wrote:Two things:

1) Your test is poor. Put a scoped variable into the session and test for that. When a session expires, the scoped variable will be gone.

2) Use a servlet filter to avoid polluting every servlet with the test.


Once again my assumptions have lead me astray. I thought the the code I was using was creating a session object instance that had to be in the servlet so I could set session attributes. Can you get me oriented again on the session object and what I should do? Where in my app do I put the scoped variable so it will be tied to the session? Where do I do the test on the scoped variable? Can you also explain item 2?
Gregg Bolinger
GenRocket Founder
Ranch Hand

Joined: Jul 11, 2001
Posts: 15300
    
    6

The answer to your doubts are kind of all inclusive if you look into Servlet Filters. Note the doFilter method that you will need to override. Since it contains a ServletRequest, you can gain access to your Session just like you would in a servlet. There are a lot of examples online of how to write a Security Filter. The gist of it is, create your Filter, override the doFilter, get the session, check for the existence of a particular key, then redirect/forward accordingly, just as you would in a Servlet.


GenRocket - Experts at Building Test Data
Steve Dyke
Ranch Hand

Joined: Nov 16, 2004
Posts: 1488
    
    1
I am working with Websphere 7.0 which has a Filters icon in the Deployment Descriptor section of the IDE but I have no idea what to do with it.
Gregg Bolinger
GenRocket Founder
Ranch Hand

Joined: Jul 11, 2001
Posts: 15300
    
    6

Steve Dyke wrote:I am working with Websphere 7.0 which has a Filters icon in the Deployment Descriptor section of the IDE but I have no idea what to do with it.


I don't either. If I were going to write a servlet filter, I'd just create a new class that Implements Filter, fill in the code, and add the Filter to the web.xml. Again, lots of examples of this compliments of Google.
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61753
    
  67

<pet-peeve-alert>
Learn how to do thing without the crutch of an IDE.
</pet-peeve-alert>
Steve Dyke
Ranch Hand

Joined: Nov 16, 2004
Posts: 1488
    
    1
Bear Bibeault wrote:Two things:

1) Your test is poor. Put a scoped variable into the session and test for that. When a session expires, the scoped variable will be gone.

2) Use a servlet filter to avoid polluting every servlet with the test.


I have a Filter class defined and added to the xml file. The filter simply displays a message when accessed.

Now how do I do what you have suggested in item 1 and 2?
Michael Angstadt
Ranch Hand

Joined: Jun 17, 2009
Posts: 274

Bear Bibeault wrote:Put a scoped variable into the session and test for that. When a session expires, the scoped variable will be gone.

Correct me if I'm wrong, but I think you could also compare the session ID in the request with the session ID of the current session. If they don't match, then you know the user's previous session was invalidated:


SCJP 6 || SCWCD 5
Gregg Bolinger
GenRocket Founder
Ranch Hand

Joined: Jul 11, 2001
Posts: 15300
    
    6

Steve Dyke wrote:
Bear Bibeault wrote:Two things:

1) Your test is poor. Put a scoped variable into the session and test for that. When a session expires, the scoped variable will be gone.

2) Use a servlet filter to avoid polluting every servlet with the test.


I have a Filter class defined and added to the xml file. The filter simply displays a message when accessed.

Now how do I do what you have suggested in item 1 and 2?


You've already done #2. For #1, when you're user logs in you can simply do something like:

session.setAttribute("something", "something else");

In your servlet, check for "something" to exist in the session. If it does, allow the filter to chain on through. If it does not, redirect to your login page.
Steve Dyke
Ranch Hand

Joined: Nov 16, 2004
Posts: 1488
    
    1
Gregg Bolinger wrote:

You've already done #2. For #1, when you're user logs in you can simply do something like:

session.setAttribute("something", "something else");

In your servlet, check for "something" to exist in the session. If it does, allow the filter to chain on through. If it does not, redirect to your login page.


Ok I'm trying but still having trouble. Here is the first servlet I call:



And the following in the filter doFilter method I get the null message for every request and response I make.

Gregg Bolinger
GenRocket Founder
Ranch Hand

Joined: Jul 11, 2001
Posts: 15300
    
    6

Are you sure this is what you need to do? How does activeSession get into the Session?

request.setAttribute("activeSession", "true");


Steve Dyke
Ranch Hand

Joined: Nov 16, 2004
Posts: 1488
    
    1
Gregg Bolinger wrote:Are you sure this is what you need to do? How does activeSession get into the Session?

request.setAttribute("activeSession", "true");




I have changed it to



I still get the null message from my filter.
Amit Ghorpade
Bartender

Joined: Jun 06, 2007
Posts: 2718
    
    6

Steve Dyke wrote:

I have changed it to




Allright, but from where is the filter reading the attribute??


SCJP, SCWCD.
|Asking Good Questions|
Roshan Ramesh
Greenhorn

Joined: Jul 12, 2010
Posts: 8
Hi Steve

It seems like you are trying to write a program that needs to be notified when the Session Expires or is Invalidated.

Apart from Filters, there are ServletListeners too that could resolve your problem. (hopefully)

Try implementing a javax.servlet.http.HttpSessionListener & declare the same in your deployment descriptor. You need to provide implementation for 2 of its mandatory methods sessionCreated() & sessionDestroyed(). For your requirement, The sessionDestroyed() is passed a HttpSessionEvent Object by the container. You can retrieve the session related stuffs (seriously) from this object.

Any good HttpServlet material will give you an example implementation of HttpSessionListener. Just follow it & do whatever you want in those 2 methods.

Have a Good Time Ahead
Ben Souther
Sheriff

Joined: Dec 11, 2004
Posts: 13410

Roshan,
Welcome to Javaranch.
It doesn't sound like the original poster (OP) wants to be notified when a session expires.
It sounds like he wants to test for an expired session before processing a request.
In this case, following Bear's original suggestion (bind a variable to session scope and test for it in a filter) is the OPs best course of action.


Java API J2EE API Servlet Spec JSP Spec How to ask a question... Simple Servlet Examples jsonf
Steve Dyke
Ranch Hand

Joined: Nov 16, 2004
Posts: 1488
    
    1
Ben Souther wrote:bind a variable to session scope


Does the following do this?

Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61753
    
  67

Yes.

Generally, I put something more meaningful in session scope than a boolean. At minimum the id of the logged-in user, but generally an "authentication token" that contains useful information about the logged-in user (a permissions map, for example).
Steve Dyke
Ranch Hand

Joined: Nov 16, 2004
Posts: 1488
    
    1
Bear Bibeault wrote:Yes.

Generally, I put something more meaningful in session scope than a boolean. At minimum the id of the logged-in user, but generally an "authentication token" that contains useful information about the logged-in user (a permissions map, for example).


Ok. My application flow is index.jsp which makes a JSON call to a SetDefaultsServlet that sets the session attribute.

Now how do I set up my filter to read this attribute?

Right now in my Filter class I have:



In my xml I have:



For every servlet call I get the Active Connection is null!. Even the initial call to the SetDefaultsServlet.
Steve Dyke
Ranch Hand

Joined: Nov 16, 2004
Posts: 1488
    
    1
Bear Bibeault wrote:Yes.

Generally, I put something more meaningful in session scope than a boolean. At minimum the id of the logged-in user, but generally an "authentication token" that contains useful information about the logged-in user (a permissions map, for example).


Ok I finally got it to work but I need a little more help. Not every one is required to log on to my app. But I set many session attributes as soon as the app starts that are used through out the app. Logging on gives more authority to the user according to their pre assigned roles. If I set my applicationActive session attribute in the first servlet and the filter checkes the value it will always return null because it fires before the attribute is set. How can I handle this and also have no-logged on users restart the app and logged on users just logg on again?
Shailesh Narkhede
Ranch Hand

Joined: Jul 10, 2008
Posts: 368
Hi Steve,

you can use HttpSession's isNew Method,
In filter get session by request.getSession(true);
& then check for session.isNew() if true forword to login page.

HTH.


Thanks,
Shailesh
Ben Souther
Sheriff

Joined: Dec 11, 2004
Posts: 13410

Shailesh Narkhede wrote:Hi Steve,

you can use HttpSession's isNew Method,
In filter get session by request.getSession(true);
& then check for session.isNew() if true forword to login page.

HTH.


I wouldn't advise using the isNew property for this.
First, it only tells you if the JSP session is new; it doesn't tell you whether or not the user has completed your login.
Second, in an app with JSPs isNew is almost always unreliable. JSPs by default generate a new session when they're hit (unless a session already exists) so the chances of the session actually being new when you get to your test are mixed at best.

Again, follow the advice Bear gave. It's solid, simple, and the way thousands of production quality apps are doing it right now.
Steve Dyke
Ranch Hand

Joined: Nov 16, 2004
Posts: 1488
    
    1
Ben Souther wrote:

Again, follow the advice Bear gave. It's solid, simple, and the way thousands of production quality apps are doing it right now.


I realize this is the best approach and I am tryng to implement it. But I still need help.

With the filter every Servlet passes through it, even the initial Servlet that declares the test session attribute. If the test says re-direct if test fails the first Servlet will fail before it gets a chance to set the session attribute. How do I exclude the initial Servlet for this test? Or can the session attribute be set before the Servlet is called?
Ben Souther
Sheriff

Joined: Dec 11, 2004
Posts: 13410

Steve Dyke wrote:...
With the filter every Servlet passes through it, ...


Not necessarily.
What gets filtered, depends on your filter's mappings in web.xml.
If possible create url-patterns that don't include the initial servlet.

If that's not possible or easy to do, in your filter, read the request URL and explicitly exclude whatever patterns you need to ignore.

Psedocode (assumes the URL for your login page ends with "login":
Steve Dyke
Ranch Hand

Joined: Nov 16, 2004
Posts: 1488
    
    1
Ben Souther wrote:
If that's not possible or easy to do, in your filter, read the request URL and explicitly exclude whatever patterns you need to ignore.


Thanks, I have everything working great except my initial logon uses $.getJSON which does not push out to a JSP but a callback in my js which then loads the page.
How would I use forward on failure in this case.
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61753
    
  67

I return a special error code that triggers an ajaxError event and handle it in script.
Steve Dyke
Ranch Hand

Joined: Nov 16, 2004
Posts: 1488
    
    1
Bear Bibeault wrote:I return a special error code that triggers an ajaxError event and handle it in script.


Thanks Bear and all the others for your help. It looks like I got what I need, for now at least.
Steve Dyke
Ranch Hand

Joined: Nov 16, 2004
Posts: 1488
    
    1
Well I thought I was done until I tried this on the Production Application Server. It works great on the Development Server.

On the Production Server I get an immediate display of my TimedOutDisplayForm.

Here is my filter code:



Never mind I think I found the problem. I was used to calling app like:

http://gvas400.webergv.weber-intranet:10000/FAIWebApp/

But instead this works:

http://gvas400.webergv.weber-intranet:10000/FAIWebApp/index.jsp
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Checking for Session Timeout