All ArticlesJEE

Maintaining sessions with ajax polling and servlets

Depending on the amount of concurrent users (and therefore numbers of sessions) and the usage of session data your web application might require lots of server resources during the lifetime of a session. Therefore it´s a good advice to set the session lifetime to an agreeable short value. However web applications might require longer session lifetimes. Just think of a blog system where you might edit articles without server-interaction and you want the session to be still alive when posting your changes to the server after some minutes.

This article shows an approch for keeping the session lifetime short in general but allow longer session lifetimes if needed for usability reasons.

The idea

The question of how long an application session must be available can often be answered with: as long as the browser window is open. We use this fantastic insight to implement or solution.The idea is to keep the session alive by polling to a session maintainting servlet in regular intervals. This will be done via ajax in the background.

Implementation

The implementation consists of two parts:

  • the client part (javascript + ajax)
  • the server part (servlet)

First we use jQuery with it´s ajax functions to implement the client part which does an interval polling - here is the ajax code:

<script type="text/javascript">

     // poll interval in ms
     var pollInt = 10000;
	 
     // setup the interval poll
     window.setInterval("jQuery.ajax({url:'/sessionKeepAlive'})", pollInt);
	 
</script>
  • the ajax poll makes a GET request to '/sessionKeepAlive' - a servlet will listen to this url and maintain the session (see below)
  • the interval of the ajax polls must be lower than the session lifetime (e.g. pollInt = sessionTTL / 2, to poll twice per session lifetime) to prevent the session from expiring.
  • as a conclusion you should not set your session lifetime too low in order to produce too many ajax polls to your server.
  • this code snipped can be embedded to all your application pages by putting it in your main template or you just put it on sites that requires a longer session lifetime for usability reasons.

Second, on the server side, we have to deploy a minimalistic http servlet that keeps the session alive and responds with a 204 status code (request ok, but no content in response):

public class SessionKeepAliveServlet extends HttpServlet
{
    private static final Logger logger           = Logger.getLogger(SessionKeepAliveServlet.class);

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        logger.debug("session keep alive poll");
        
        // access the session without creating it - this maintains the session
        request.getSession(false); 

        // send a 204
        response.setStatus(HttpServletResponse.SC_NO_CONTENT); 
    }
}

The servlet must be registered in your web.xml and listen to the url the ajax poll requests to ('/sessionKeepAlive'):

...
<servlet>
	<servlet-name>SessionKeepAliveServlet</servlet-name>
	<servlet-class>your.package.SessionKeepAliveServlet</servlet-class>
</servlet>

<servlet-mapping>
	<servlet-name>SessionKeepAliveServlet</servlet-name>
	<url-pattern>/sessionKeepAlive</url-pattern>
</servlet-mapping>
...

And this is it!

Now you can set your application´s session lifetime to a short value (like 5 minutes). Sessions will remain alive while the browser window is open because the ajax polling is active in the background. When closing the browser window or changing the current url the session will expire in a short period of time.

One drawback of the this approach is, that open browser windows block application server resources even if users are not really active anymore (surfing on facebook meanwhile in another tab). To handle this, your application requires more logic, e.g. implement a longtime session timeout that expires only after x ajax polls and no user interaction etc.

Well, consider your application, the usage of session data, concurrent users and required usability to decide if this approach might be a solution for maintaining the session when needed but keeping the session lifetime short in general.

 

Note for JSF developers that use Richfaces: You could also use the <a4j:poll> component to achieve the same. Compared to the implementation showed here this has 2 disadvantages. First it generates more overhead on the server side because the jsf lifecycle is fully performed and second you have to synchronize possible parallel ajax calls with a queue.

About this Article

jan.ziegler: Maintaining sessions with ajax polling and servlets

written by: jan.ziegler on 25 Jan 2011

tags used: Ajax, Poll, Session

news stored under: JEE

share this article:

Comments (0)

Tell us what you think!