`
clin8888
  • 浏览: 55864 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

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

 

代码:

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[i];
                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 楼 superbase 2010-11-19  
通过验证了吗?
6.0.18无法失败,无法共享SESSION。

相关推荐

    Tomcat二级域名Session共享例子

    Tomcat二级域名Session共享例子,具体操作看博客:http://blog.csdn.net/luogqing/article/details/78595200

    Java Tomcat二级域名Session共享例子

    Tomcat二级域名Session共享例子,具体操作看博客:http://blog.csdn.net/luogqing/article/details/78595200

    tomcat二级域名session共享包

    方便新手使用的tomcat二级域名所需要的包.. 详细的使用方法.查看.. http://blog.csdn.net/wqfeng520/archive/2010/11/29/6042596.aspx

    集中式session管理方案(2)

    - 多应用共享Session:当用户在多个应用间切换时,需要保持相同的登录状态和个性化设置。 - 多服务器共享Session:在负载均衡的环境下,用户可能会被重定向到不同的服务器,但Session数据需保持一致。 2. **适用...

    2021-2022计算机二级等级考试试题及答案No.5537.docx

    根据提供的文档内容,我们可以总结出一系列与计算机二级等级考试相关的知识点。这些知识点涵盖了排序算法、JSP动作、C语言基础知识、Python编程、网络协议、Web应用开发、数据库设计等多个方面。 ### 排序算法 **...

    sso单点登录(整理的学习文档)

    设置Cookie的域为`setDomain(".example.com")`,使得该Cookie可以在所有`.example.com`下的二级域名中有效。 3. 修改主机文件(例如Windows下的`C:\Windows\System32\drivers\etc\hosts`),添加必要的DNS条目以...

    SpringMVC-Mybatis-Shiro-redis-master 权限集成缓存中实例

    上面配置是去掉了 Session 的存储Key 的作用域,之前设置的.itboy.net ,是写到当前域名的 一级域名 下,这样就可以做到N 个 二级域名 下,三级、四级....下 Session 都是共享的。 &lt;!-- 用户信息记住我功能的...

    JAVA程序开发技术

    - **方法**:`&lt;input type="hidden" name="sessionID" value="${session.id}"&gt;`. **5.6.3 用Session控制会话** - **类`HttpSession`**: - 获取:`request.getSession()`; - 设置属性:`session.setAttribute...

    Java开发技术大全 电子版

    10.10.1静态成员共享问题325 10.10.2重载冲突问题325 10.10.3接口实现问题326 10.11泛型的局限326 10.11.1不能使用基本类型326 10.11.2不能使用泛型类异常326 10.11.3不能使用泛型数组327 10.11.4不能实例化...

    基于J2EE框架的个人博客系统项目毕业设计论文(源码和论文)

    第二章 系统设计 2.1. 系统分析 在整个blog进行开发之前,要确定出整个项目的整体架构,包括系统的选型、运行环境的确定及系统结构设计。下面对这进行详细介绍。 在进行软件系统开发的最初环节,一般都需要进行...

    Jetty权威指南.pdf

    - **轻量级**:相比于其他大型服务器如Apache Tomcat,Jetty体积更小、占用资源更少,特别适合于嵌入式环境或资源有限的设备。 - **高性能**:Jetty采用异步处理机制,能够高效处理大量并发连接,尤其适用于高负载的...

    单点登录源码

    通用用户管理系统, 实现最常用的用户注册、登录、资料管理、个人中心、第三方登录等基本需求,支持扩展二次开发。 &gt; zheng-wechat-mp 微信公众号管理平台,除实现官网后台自动回复、菜单管理、素材管理、用户管理...

Global site tag (gtag.js) - Google Analytics