【编者按】:网学网JAVA为您提供tomcat 二级域名 共享session 的方法参考,解决您在tomcat 二级域名 共享session 的方法学习中工作中的难题,参考学习。
Tomcat下,不同的二级域名,Session默认是不共享的,因为Cookie名称为JSESSIONID的Cookie根域是默认是没设置的,访问 不同的二级域名,其Cookie就重新生成,而session就是根据这个Cookie来生成的,所以在不同的二级域名下生成的Session也不一样。 找到了其原因,就可根据这个原因对Tomcat在生成Session时进行相应的修改(注:本文针对Tomcat 6.0)。 单个web项目运行在tomcat上但是却使用多个子域名,如: - site.com - www.site.com - sub1.site.com - sub2.site.com - etc. 这样会导致session的不能共享,在网络上查找的并却最快的解决办法。 解决办法:Usage: - compile CrossSubdomainSessionValve & put it in a .jar file - put that .jar file in $CATALINA_HOME/lib directory - include a <Valve className="org.three3s.valves.CrossSubdomainSessionValve"/> in $CATALINA_HOME/conf/server.xml Java代码 package org.three3s.valves; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import org.apache.catalina.*; import org.apache.catalina.connector.*; import org.apache.catalina.valves.*; import org.apache.tomcat.util.buf.*; import org.apache.tomcat.util.http.*; /** <p>Replaces the domain of the session cookie generated by Tomcat with a domain that allows that * session cookie to be shared across subdomains. This valve digs down into the response headers * and replaces the Set-Cookie header for the session cookie, instead of futilely trying to * modify an existing Cookie object like the example at http://www.esus.be/blog/?p=3. That * approach does not work (at least as of Tomcat 6.0.14) because the * <code>org.apache.catalina.connector.Response.addCookieInternal</code> method renders the * cookie into the Set-Cookie response header immediately, making any subsequent modifying calls * on the Cookie object ultimately pointless.</p> * * <p>This results in a single, cross-subdomain session cookie on the client that allows the * session to be shared across all subdomains. However, see the {@link getCookieDomain(Request)} * method for limits on the subdomains.</p> * * <p>Note though, that this approach will fail if the response has already been committed. Thus, * this valve forces Tomcat to generate the session cookie and then replaces it before invoking * the next valve in the chain. Hopefully this is early enough in the valve-processing chain * that the response will not have already been c