5

I am using tomcat 7.0.6 with jdk 1.6.0_22

Is it possible to share session data between 2 different domains with a common subdomain such as a.mydomain.com and b.mydomain.com ?

With the default java servlet a.mydomain.com and b.mydomain.com get different sessions, but is it not possible to create a shared session for all subdomains in mydomain.com?

The problem is also that I don't directly control the commen subdomain (mydomain.com) so I can't serve any servlets from mydomain.com

lesmana
  • 22,750
  • 8
  • 73
  • 83
MTilsted
  • 4,974
  • 9
  • 33
  • 64

3 Answers3

14

Set the sessionCookieDomain attribute of <Context> element of the webapp in question to .mydomain.com (note the leading dot, this is very important). This will allow the webbrowser to share cookies among all subdomains.

If you actually have multiple webapp contexts and you want to share the session between them as well, then you also need to set sessionCookiePath attribute of <Context> element of the webapps in question to /.

In a nutshell:

<Context sessionCookieDomain=".mydomain.com" sessionCookiePath="/">

See also:


For Tomcat 6 users: note that this was introduced in Tomcat 6.0.27. For those who can't upgrade, you would need a Valve to modify the cookie domain, eventually in combination with emptySessionPath attribute in <Connector> element in /conf/server.xml for the case that you've multiple webapp contexts for which you'd like to share the session.

BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
  • Cool. I just upgraded to tomcat 7 a few days ago, and had not noticed that they added that feature – MTilsted Jan 28 '11 at 05:02
  • @BalusC If i set an attribute from one webapp in session, would i able to get that attribute from other webapp, after setting cookiePath to "/" – Shadow Aug 26 '14 at 11:12
3

Servlet Spec 3.0 (which is what Tomcat 7 supports) allows this by calling setDomain on SessionCookieConfig.

Details here: http://download.oracle.com/javaee/6/api/javax/servlet/SessionCookieConfig.html

You get SessionCookieConfig progammatically at webapp init time with a ServletContextListner - or you should be able to set it the value in web.xml.

Tim Funk
  • 819
  • 7
  • 11
0

You can create your own session implementation using cookies. Sessions are handled (in most server side languages) using cookies and server side database or files. You create a token (using md5 on timestamp) and save it in file or database along with all session variables.

jcubic
  • 51,975
  • 42
  • 183
  • 323