/ blog / java / proxied-servlet-sessions.html

Root Beer Logo Root Beer

Chris Nokleberg's Fizzy Weblog

May 2003
Su M Tu W Th F Sa
        1 2 3
4 5 6 7 9 10
11 13 14 15 16 17
18 19 20 21 22 24
25 26 27 28 29 30 31
Previous  |  Next  |  More...
#  Making sessions work in proxied applications

A preferred architecture of mine is to run Apache as a front-end webserver, and to use mod_proxy to connect to a servlet container. Some of the benefits are:

  • Lets you leverage all of the features of Apache (gzipping content, SSL, logging, etc.) while keeping your servlet configuration simple.
  • You don't have to hassle with running the servlet container on a privileged port.
  • It is possible to serve all static content through Apache, leaving only the dynamic pages to the backend, which can improve overall performance.

One major problem with this approach, however, is session handing. The servlet containers set a cookie named "JSESSIONID" to track your session, and the path used for the cookie is the context path of the application. Of course, in a proxy situation, the context path may not match the actual path used to access the application. For example, on this site I proxy everything from to http://localhost:8080/blojsom/blog/. Under normal circumstances, the path of the cookie will be "/blojsom", and the end result is that the browser will never send back the session cookie, leading to a new session being created on every request.

One suggestion was to ensure that the public URL to your application matches the context path. Needless to say I wasn't satisfied with that answer!

My first approach was to write a servlet filter to wrap the response object, and modify the path of the session cookie when it was set by the container. Unfortunately, it appears that at least Tomcat does not use the wrapped response object in setting the cookie [Emoticon]. This could be construed as a bug, but I don't have the energy to argue that with anyone.

Luckily, in my application I have a centralized piece of code which is responsible for creating all sessions, so the workaround is to just manually set an additional cookie with the correct path:

if (session.isNew()) {
    Cookie cookie = new Cookie("JSESSIONID", session.getId());

This results in two JSESSIONID cookies actually being sent. It works, but I wish there was a more elegant solution.

[Powered By FreeMarker]  [Valid Atom 1.0]  [Weblog Commenting by]