Java HttpSession done right

Dealing with problems with Tomcat session manager
Solution with Spring Session as session tier
and Redis database as session store

The Problem

In web applications, there are always data needed to be stored in http session. Java uses javax.servlet.http.HttpSession class for this. But this interface also needs implementation, which will take data we want in session, bind it with some unique session identifier, and store it in memory or on disc for later usage.
This implementation is usually web container specific. As the most java web applications use Tomcat as container, there this concept is known as Session management component and implemented in org.apache.catalina.session.StandardManager class.

This usually works well. Especially if you run it on local machine with single Tomcat server instance, during development. But problem might arise in production. Web container might not be Tomcat, but some other servlet, Java EE or web profile implementation. In cloud environments, there can be multiple server instances where our web application is deployed. Requests from one user should be served from the same instance, but for various reasons this may be not the case.
All this leads to lost session data. Which is also hard to spot, as everything works well in local environment. And there are no server errors, just HttpSession attributes are not there. This happened to me with Openshift online cloud environment. Hence, I applied approach described here and solved the problem.

Solution and implementation

As with many other things, guys from Spring recognized this problem and came with unified neat solution. It's Spring Session project. I already use Spring as basic app container and web mvc framework, so using Spring Session introduces little changes.
And as sessions need to be stored in some kind of data management tool, Spring chose Redis for this.

All the wiring and configuration is explained here.
It's all well explained, but if you run into problems making everything work as I did, here are few hints:

  • Spring Session works well with Redis versions 2.8 and above, so make sure to install one of these
  • The same is true if you use Openshift as deploy platform. Redis is available as cartridge, but there are several of them. Find one which installs Redis 2.8+
  • When you install Redis on Openshift, JedisConnectionFactory described in article above must also be configured to use specific port and host. It should be configured like this
    <bean class=""