Session wrapper.


    It is a Java class allows you to catch session timeout in your servlets. The idea is very simple. This class just wraps all standard calls for HttpSession API and contains thread for checking in the background  session timeout. In case timeout occurs or you directly call invalidate() this class call abstract method void timeout(HttpSession). So you can redefine this method and set some actions should be done before session expiration.

    The reason we are using this class is some problems with the standard servlets API. Normally we should use HttpSessionBindingListener and catch HttpSessionBindingEvents. But looks like it not woks for all implementations. The second reason - even if it works valueUnbound() will be called after session invalidation. So at this moment you already lost the ability to access to your session objects. In our approach you will get your current session in non-invalidated state. So you can for example close some objects saved in your session and after that call invalidate().

For example:

import javax.servlet.*;
import javax.servlet.http.*;

public class MySession extends ServletSession
{
 public MySession(HttpServletRequest req, long timeout_in_seconds)
 {
  super(req,tm);
 }

 public void timeout(HttpSession sess)
 {
System.out.println("timeout. Close connections, clear objects etc...");
  sess.invalidate();
 }
}

and you servlets code looks like:

 public void doGet (HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException
    {

     // session object. Timeout is 10 minutes
     // note - does not create a session here !
     MySession ms=new MySession(req,600);
 

     // now we create the session
     ms=(MySession)ms.getSession(true);
     if (ms.isNew())
     {
       ms.putValue("user_name","guest);
       ....
       }
     else
     {
       String s=(String)ms.getValue("user_name");

      }
    }
 

Class ServletSession has got one abstract method (it is our callback):
    public void timeout(HttpSession)

Constructor for ServletSession has got 2 parameters:
    public ServletSession(HttpServletRequest req, long timeout_in_seconds)

and one new method:
    public void setCheckingInterval(long seconds)
it is a time interval for checking session timeout. By default it is 5 seconds.

All another methods from class ServletSession are exactly the same as a methods in HttpSession interface.

Note: you can set default timeout for your servletrunner for some big value and use any smallest value in your  sessions.
 

For downloading:   ServletSession.class

© ColdJava  1999