File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Servlets and the fly likes Session timeout Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "Session timeout" Watch "Session timeout" New topic

Session timeout

Ian Morris

Joined: May 23, 2001
Posts: 7
I have developed a number of servlets and jsp's that require a user to login to the application.
I have a session to hold the login details, however, I have a come across a problem which I assume is down to the session timing out. I get a null pointer exception error, this I believe is when I try and access the session that holds the user details.
I have set the session.setMaxInactiveInterval(10) to prove this. I have looked for a way to check to see if the session is still valid before trying to access any details held in it but do not know how to do this, I thought I could simply type 'if (session != null)', but this fails.
Can anybody help?
Jack Wiesenthaler
Ranch Hand

Joined: Jul 26, 2001
Posts: 75
catch IllegalStateException to check for an expired session
Vlad Patryshev
Ranch Hand

Joined: Jun 30, 2001
Posts: 61
You have to have a class that is
public class <yourclassname> implements HttpSessionBindingListener
(I declare my application bean this way.)

And then add two methods, something like the following:

public void register(HttpSession session) {
if (session.getAttribute("application") == null) {
session.setAttribute("application", this);
session.setMaxInactiveInterval(1800); /* Give them half an hour before committing the stuff */
public String unregister(HttpSession session) {
String id = session.getId();
ArrayList tables = (ArrayList)sessions.get(id);
System.err.println("unregistering session " + id + ", tables = " + tables);
if (tables != null) {
System.err.println("In total have " + ((ArrayList)sessions.get(session.getId())).size() + " in " + sessions);
addErrorMessage("<br>" + build(tables) + "<br>");
return "committed.";

public void valueBound(HttpSessionBindingEvent event) {
// addErrorMessage((new Date()).toString() + ": binding " + event.getSession().getId() + "<br>");
String id = event.getSession().getId();
if (sessions.get(id) == null) {
sessions.put(id, new ArrayList());
public void valueUnbound(HttpSessionBindingEvent event) {
Hope you got the general idea - if you have session timeout, you will probably need to react when it happens.
Sorry, it is just a piece of my actual code

Thanks,<br />Vlad
Katie McCann
Ranch Hand

Joined: Jul 24, 2000
Posts: 45

Get your session like this:
HttpSession session= request.getSession(false);
Giving it the "false" flag will *NOT* create a new session if one is not found, so then you can just do:
if (session !=null)
I agree. Here's the link:
subject: Session timeout
jQuery in Action, 3rd edition