Sharing session data between contexts in Tomcat

To my knowledge there is no direct way to do this, you can however use a domain level cookie if these contexts share the same domain.

You can either put the data in the cookie (I don't recommend that).

Or put a secured session Id that you can use to access some form of storage (DB or distributed cache etc) to retrieve the data you need.


If the amount of data is not astronomical and the data itself isn't changing too rapidly, you might want to consider using JNDI. This solution was designed exactly for what you are looking for.

You can have a look at official documentation or this post to tomcat-user mailing list for references & examples.


That article is indeed heavily outdated.

On Tomcat 5.5 and 6.0 you can just set emptySessionPath attribute to true in the <Connector> element in /conf/server.xml.

<Connector ... emptySessionPath="true">

On Tomcat 7.0 this has changed because this is now configureable from the Servlet 3.0 API on. It's then on Tomcat's side configureable by setting sessionCookiePath to / in <Context> element in any responsible context.xml file.

<Context ... sessionCookiePath="/">

As said, there's a new Servlet 3.0 API which allows you to configure the session cookie through the standard API. You can do it either declaratively by adding the following to the web.xml:

<session-config>
    <cookie-config>
        <path>/</path>
    </cookie-config>
</session-config>

or programmatically by SessionCookieConfig which is available by ServletContext#getSessionCookieConfig().

getServletContext().getSessionCookieConfig().setPath("/");

You could do this in ServletContextListener#contextInitialized() or HttpServlet#init().

See also:

  • Tomcat 5.5 HTTP connector documentation
  • Tomcat 6.0 HTTP connector documentation - mentions potential security hole
  • Tomcat 7.0 context documentation