设为首页 收藏本站
查看: 546|回复: 0

[经验分享] tomcat 二级域名 共享session 方法

[复制链接]

尚未签到

发表于 2017-1-29 08:51:16 | 显示全部楼层 |阅读模式
  
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


  代码:

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 committed.  You are
advised to define this
* valve as early as possible in server.xml to ensure that the
response has not already been
* committed when this valve is invoked.</p>
*
* <p>We recommend that you define this valve in server.xml
immediately after the Catalina Engine
* as follows:
* <pre>
* <Engine name="Catalina"...>
*     <Valve className="org.three3s.valves.CrossSubdomainSessionValve"/>
* </pre>
* </p>
*/
public class CrossSubdomainSessionValve extends ValveBase
{
public CrossSubdomainSessionValve()
{
super();
info = "org.three3s.valves.CrossSubdomainSessionValve/1.0";
}
@Override
public void invoke(Request request, Response response) throws
IOException, ServletException
{
//this will cause Request.doGetSession to create the session
cookie if necessary
request.getSession(true);
//replace any Tomcat-generated session cookies with our own
Cookie[] cookies = response.getCookies();
if (cookies != null)
{
for (int i = 0; i < cookies.length; i++)
{
Cookie cookie = cookies;
containerLog.debug("CrossSubdomainSessionValve: Cookie
name is " + cookie.getName());
if (Globals.SESSION_COOKIE_NAME.equals(cookie.getName()))
replaceCookie(request, response, cookie);
}
}
//process the next valve
getNext().invoke(request, response);
}
/** Replaces the value of the response header used to set the
specified cookie to a value
* with the cookie's domain set to the value returned by
<code>getCookieDomain(request)</code>
*
* @param request
* @param response
* @param cookie cookie to be replaced.
*/
@SuppressWarnings("unchecked")
protected void replaceCookie(Request request, Response response,
Cookie cookie)
{
//copy the existing session cookie, but use a different domain
Cookie newCookie = new Cookie(cookie.getName(), cookie.getValue());
if (cookie.getPath() != null)
newCookie.setPath(cookie.getPath());
newCookie.setDomain(getCookieDomain(request));
newCookie.setMaxAge(cookie.getMaxAge());
newCookie.setVersion(cookie.getVersion());
if (cookie.getComment() != null)
newCookie.setComment(cookie.getComment());
newCookie.setSecure(cookie.getSecure());
//if the response has already been committed, our replacement
strategy will have no effect
if (response.isCommitted())
containerLog.error("CrossSubdomainSessionValve: response
was already committed!");
//find the Set-Cookie header for the existing cookie and
replace its value with new cookie
MimeHeaders headers = response.getCoyoteResponse().getMimeHeaders();
for (int i = 0, size = headers.size(); i < size; i++)
{
if (headers.getName(i).equals("Set-Cookie"))
{
MessageBytes value = headers.getValue(i);
if (value.indexOf(cookie.getName()) >= 0)
{
StringBuffer buffer = new StringBuffer();
ServerCookie.appendCookieValue(buffer,
newCookie.getVersion(), newCookie
.getName(), newCookie.getValue(),
newCookie.getPath(), newCookie
.getDomain(), newCookie.getComment(),
newCookie.getMaxAge(), newCookie
.getSecure());
containerLog.debug("CrossSubdomainSessionValve:
old Set-Cookie value: "
+ value.toString());
containerLog.debug("CrossSubdomainSessionValve:
new Set-Cookie value: " + buffer);
value.setString(buffer.toString());
}
}
}
}
/** Returns the last two parts of the specified request's server
name preceded by a dot.
* Using this as the session cookie's domain allows the session to
be shared across subdomains.
* Note that this implies the session can only be used with
domains consisting of two or
* three parts, according to the domain-matching rules specified
in RFC 2109 and RFC 2965.
*
* <p>Examples:</p>
* <ul>
* <li>foo.com => .foo.com</li>
* <li>www.foo.com => .foo.com</li>
* <li>bar.foo.com => .foo.com</li>
* <li>abc.bar.foo.com => .foo.com - this means cookie won't work
on abc.bar.foo.com!</li>
* </ul>
*
* @param request provides the server name used to create cookie domain.
* @return the last two parts of the specified request's server
name preceded by a dot.
*/
protected String getCookieDomain(Request request)
{
String cookieDomain = request.getServerName();
String[] parts = cookieDomain.split("\\.");
if (parts.length >= 2)
cookieDomain = parts[parts.length - 2] + "." +
parts[parts.length - 1];
return "." + cookieDomain;
}
public String toString()
{
return ("CrossSubdomainSessionValve[container=" +
container.getName() + ']');
}
}

 

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-334743-1-1.html 上篇帖子: [原创]基于TOMCAT的安全认证 下篇帖子: jconsole_tomcat 基于jdk1.5--3
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表