• 同一服务器不同域名session共享


    Tomcat下,不同的二级域名之间或根域与子域之间,Session默认是不共享的,因为Cookie名称为JSESSIONID的Cookie根域是默认是没设置 的,访问不同的二级域名,其Cookie就重新生成,而session就是根据这个Cookie来生成的,所以在不同的二级域名下生成的Session也 不一样。找到了其原因,就可根据这个原因对Tomcat在生成Session时进行相应的修改(注:本文针对Tomcat 6.0.18)。

    方案一:

    修改tomcat源代码 包:catalina.jar 
    类:org.apache.catalina.connector.Request

    [java] view plaincopy在CODE上查看代码片派生到我的代码片
    1. protected void configureSessionCookie(Cookie cookie) {         
    [java] view plaincopy在CODE上查看代码片派生到我的代码片
    1.   cookie.setMaxAge(-1);   
    2.         String contextPath = null;   
    3.         if (!connector.getEmptySessionPath() && (getContext() != null)) {   
    4.             contextPath = getContext().getEncodedPath();         
    [java] view plaincopy在CODE上查看代码片派生到我的代码片
    1.   }   
    2.         if ((contextPath != null) && (contextPath.length() > 0)) {         
    [java] view plaincopy在CODE上查看代码片派生到我的代码片
    1.       cookie.setPath(contextPath);          
    [java] view plaincopy在CODE上查看代码片派生到我的代码片
    1.  } else {   
    2.             cookie.setPath("/");         }   
    3.         String value = System.getProperty("webDomain");       
    [java] view plaincopy在CODE上查看代码片派生到我的代码片
    1.     if ((null !=value) && (value.length()>0) && (value.indexOf(".") != -1)) {   
    [java] view plaincopy在CODE上查看代码片派生到我的代码片
    1.             cookie.setDomain((value.startsWith("."))?value:"."+value);       
    [java] view plaincopy在CODE上查看代码片派生到我的代码片
    1.     }   
    2.         if (isSecure()) {   
    3.             cookie.setSecure(true);         }     
    [java] view plaincopy在CODE上查看代码片派生到我的代码片
    1.   }  


    重新编译Tomcat:编译tomcat  
    修改配置:tomcatconfcatalina.properties,在最后添加一行 webDomain=***.com

     

    方案二:

    网上其他方案

    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] view plaincopy在CODE上查看代码片派生到我的代码片
    1. package org.three3s.valves;  
    2.   
    3. import java.io.*;  
    4.   
    5. import javax.servlet.*;  
    6. import javax.servlet.http.*;  
    7.   
    8. import org.apache.catalina.*;  
    9. import org.apache.catalina.connector.*;  
    10. import org.apache.catalina.valves.*;  
    11. import org.apache.tomcat.util.buf.*;  
    12. import org.apache.tomcat.util.http.*;  
    13.   
    14. /** <p>Replaces the domain of the session cookie generated by Tomcat 
    15. with a domain that allows that 
    16.  * session cookie to be shared across subdomains.  This valve digs 
    17. down into the response headers 
    18.  * and replaces the Set-Cookie header for the session cookie, instead 
    19. of futilely trying to 
    20.  * modify an existing Cookie object like the example at 
    21. http://www.esus.be/blog/?p=3.  That 
    22.  * approach does not work (at least as of Tomcat 6.0.14) because the 
    23.  * <code>org.apache.catalina.connector.Response.addCookieInternal</code> 
    24. method renders the 
    25.  * cookie into the Set-Cookie response header immediately, making any 
    26. subsequent modifying calls 
    27.  * on the Cookie object ultimately pointless.</p> 
    28.  * 
    29.  * <p>This results in a single, cross-subdomain session cookie on the 
    30. client that allows the 
    31.  * session to be shared across all subdomains.  However, see the 
    32. {@link getCookieDomain(Request)} 
    33.  * method for limits on the subdomains.</p> 
    34.  * 
    35.  * <p>Note though, that this approach will fail if the response has 
    36. already been committed.  Thus, 
    37.  * this valve forces Tomcat to generate the session cookie and then 
    38. replaces it before invoking 
    39.  * the next valve in the chain.  Hopefully this is early enough in the 
    40. valve-processing chain 
    41.  * that the response will not have already been committed.  You are 
    42. advised to define this 
    43.  * valve as early as possible in server.xml to ensure that the 
    44. response has not already been 
    45.  * committed when this valve is invoked.</p> 
    46.  * 
    47.  * <p>We recommend that you define this valve in server.xml 
    48. immediately after the Catalina Engine 
    49.  * as follows: 
    50.  * <pre> 
    51.  * <Engine name="Catalina"...> 
    52.  *     <Valve className="org.three3s.valves.CrossSubdomainSessionValve"/> 
    53.  * </pre> 
    54.  * </p> 
    55.  */  
    56. public class CrossSubdomainSessionValve extends ValveBase  
    57. {  
    58.     public CrossSubdomainSessionValve()  
    59.     {  
    60.         super();  
    61.         info = "org.three3s.valves.CrossSubdomainSessionValve/1.0";  
    62.     }  
    63.   
    64.     @Override  
    65.     public void invoke(Request request, Response response) throws  
    66. IOException, ServletException  
    67.     {  
    68.         //this will cause Request.doGetSession to create the session  
    69. cookie if necessary  
    70.         request.getSession(true);  
    71.   
    72.         //replace any Tomcat-generated session cookies with our own  
    73.         Cookie[] cookies = response.getCookies();  
    74.         if (cookies != null)  
    75.         {  
    76.             for (int i = 0; i < cookies.length; i++)  
    77.             {  
    78.                 Cookie cookie = cookies[i];  
    79.                 containerLog.debug("CrossSubdomainSessionValve: Cookie  
    80. name is " + cookie.getName());  
    81.                 if (Globals.SESSION_COOKIE_NAME.equals(cookie.getName()))  
    82.                     replaceCookie(request, response, cookie);  
    83.             }  
    84.         }  
    85.   
    86.         //process the next valve  
    87.         getNext().invoke(request, response);  
    88.     }  
    89.   
    90.     /** Replaces the value of the response header used to set the 
    91. specified cookie to a value 
    92.      * with the cookie's domain set to the value returned by 
    93. <code>getCookieDomain(request)</code> 
    94.      * 
    95.      * @param request 
    96.      * @param response 
    97.      * @param cookie cookie to be replaced. 
    98.      */  
    99.     @SuppressWarnings("unchecked")  
    100.     protected void replaceCookie(Request request, Response response,  
    101. Cookie cookie)  
    102.     {  
    103.         //copy the existing session cookie, but use a different domain  
    104.         Cookie newCookie = new Cookie(cookie.getName(), cookie.getValue());  
    105.         if (cookie.getPath() != null)  
    106.             newCookie.setPath(cookie.getPath());  
    107.         newCookie.setDomain(getCookieDomain(request));  
    108.         newCookie.setMaxAge(cookie.getMaxAge());  
    109.         newCookie.setVersion(cookie.getVersion());  
    110.         if (cookie.getComment() != null)  
    111.             newCookie.setComment(cookie.getComment());  
    112.         newCookie.setSecure(cookie.getSecure());  
    113.   
    114.         //if the response has already been committed, our replacement  
    115. strategy will have no effect  
    116.         if (response.isCommitted())  
    117.             containerLog.error("CrossSubdomainSessionValve: response  
    118. was already committed!");  
    119.   
    120.         //find the Set-Cookie header for the existing cookie and  
    121. replace its value with new cookie  
    122.         MimeHeaders headers = response.getCoyoteResponse().getMimeHeaders();  
    123.         for (int i = 0, size = headers.size(); i < size; i++)  
    124.         {  
    125.             if (headers.getName(i).equals("Set-Cookie"))  
    126.             {  
    127.                 MessageBytes value = headers.getValue(i);  
    128.                 if (value.indexOf(cookie.getName()) >= 0)  
    129.                 {  
    130.                     StringBuffer buffer = new StringBuffer();  
    131.                     ServerCookie.appendCookieValue(buffer,  
    132. newCookie.getVersion(), newCookie  
    133.                             .getName(), newCookie.getValue(),  
    134. newCookie.getPath(), newCookie  
    135.                             .getDomain(), newCookie.getComment(),  
    136. newCookie.getMaxAge(), newCookie  
    137.                             .getSecure());  
    138.                     containerLog.debug("CrossSubdomainSessionValve:  
    139. old Set-Cookie value: "  
    140.                             + value.toString());  
    141.                     containerLog.debug("CrossSubdomainSessionValve:  
    142. new Set-Cookie value: " + buffer);  
    143.                     value.setString(buffer.toString());  
    144.                 }  
    145.             }  
    146.         }  
    147.     }  
    148.   
    149.     /** Returns the last two parts of the specified request's server 
    150. name preceded by a dot. 
    151.      * Using this as the session cookie's domain allows the session to 
    152. be shared across subdomains. 
    153.      * Note that this implies the session can only be used with 
    154. domains consisting of two or 
    155.      * three parts, according to the domain-matching rules specified 
    156. in RFC 2109 and RFC 2965. 
    157.      * 
    158.      * <p>Examples:</p> 
    159.      * <ul> 
    160.      * <li>foo.com => .foo.com</li> 
    161.      * <li>www.foo.com => .foo.com</li> 
    162.      * <li>bar.foo.com => .foo.com</li> 
    163.      * <li>abc.bar.foo.com => .foo.com - this means cookie won't work 
    164. on abc.bar.foo.com!</li> 
    165.      * </ul> 
    166.      * 
    167.      * @param request provides the server name used to create cookie domain. 
    168.      * @return the last two parts of the specified request's server 
    169. name preceded by a dot. 
    170.      */  
    171.     protected String getCookieDomain(Request request)  
    172.     {  
    173.         String cookieDomain = request.getServerName();  
    174.         String[] parts = cookieDomain.split("\.");  
    175.         if (parts.length >= 2)  
    176.             cookieDomain = parts[parts.length - 2] + "." +  
    177. parts[parts.length - 1];  
    178.         return "." + cookieDomain;  
    179.     }  
    180.   
    181.     public String toString()  
    182.     {  
    183.         return ("CrossSubdomainSessionValve[container=" +  
    184. container.getName() + ']');  
    185.     }  
    186. }  


    放入<Host>标签中,也可以放到<Engine>标签中。个人猜想:如果放入<Host>标签中应该只是当前项目的主域名和二级域名session共享,如果放到<Engine>标签中,应该是该tomcat下所有的项目都是主域名和二级域名共享(没有实验)。

     

    方便对于tomcat的二级域名的使用..而导致session失效的解决方法..

    需要引用的包是..

    下载CrossSubdomainSessionValve包.. 把下载的包,放到$CATALINA_HOME/server/lib 里面

    然后修改tomcat的配置文件: $CATALINA_HOME/conf/server.xml

    在标签"Engine",中添加依家配置标签..

    <Valve className="org.three3s.valves.CrossSubdomainSessionValve"/>  

    类似于:

    <Engine name="Catalina"...>    
           <valve className="org.three3s.valves.CrossSubdomainSessionValve"/>   

    </Engine>

     

     

    测试发现,,cookie可以共享,另外发现SESSIONID可以共享。但session中的其他内容不能共享。

     

    • 这是简单方案。 多台服务器的话,还需要配置tomcat的session复制。

     

     方案三:

    • 还有一种巧妙的单机方式

    最近在做一个jsp的网站遇到了session共享的问题,下面以一个简单的实例讲解一下其中的细节及解决方法:

    网站有两个域名:主域名www.test.com  二级域名xxx.test.com

    1、用主域名打开网站,比如访问www.test.com/login.jsp,这时会产生一个session,并将JSESSIONID=XXXXXXXXXX保存到客户端Cookie中;

    2、接着进行登陆操作,提交表单到www.test.com/checklogin.jsp,  这两次操作是在同一会话(session)下(假设没关浏览器),why?

         因为我们再通过主域访问站点的其他页面时,第一步在客户端生成的JSESSIONID(通过cookie方式,如果cookie被禁了则通过url)会提交到服务端

         用于获取对应的session对象,两次JSESSIONID一样,所以两次的会话保持一致

    3、登陆成功后去到了www.test.com/index.jsp 页面,页面打印当前的JSESSIONID=XXXXXXXXXX

    4、接着通过二级域名访问index.jsp,即xxx.test.com/index.jsp,这时页面打印的JSESSIONID=YYYYYYYYYY,也就是说再通过二级域名访问index.jsp

        这个页面时session已经改变了,即刚才的登陆对二级域名下的访问无效了,why?因为通过该二级域名访问index.jsp时,由于无法获取到主域名生成的JSESSIONID

        所以会重新生成一个session,并把JSESSIONID=YYYYYYYYYY保存到客户端。

     

    如何解决?

    我的解决方法:做一个跳转页面skip.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

    <%

     String JSESSIONID = request.getSession().getId();//获取当前JSESSIONID (不管是从主域还是二级域访问产生)

     Cookie cookie = new Cookie("JSESSIONID", JSESSIONID);
     cookie.setDomain(".test.com"); //关键在这里,将cookie设成主域名访问,确保不同域之间都能获取到该cookie的值,从而确保session统一
     response.addCookie(cookie);  //将cookie返回到客户端

     request.getRequestDispatcher("indes.jsp").forward(request, response);

    %>

     

     方案四:


    • 大型项目出于性能考虑,一般采用session分布式方案,如: 修改session实现+分布式缓存memcached

    Memcache存储session,修改tomcat源码,实现全站二级域名session共享http://blog.csdn.net/jimmy1980/article/details/4975476
    使用memcache实现session共享 http://blog.csdn.net/jimmy1980/article/details/4981410

     

     

     

     

     

    ------------------------------------------other  start--------------------------------------------------

    让tomcat支持2级域名共享session

    最近启用二级域名后,面临一个主域名与二级域名之间 session 不能共享的问题,带来的麻烦就是用户在主域名登陆,但由于二级域名 session 不能共享 ,因此无法进行登陆的操作,对一些功能有一些影响。

    问题的原因如下
    Tomcat 下,不同的二级域名,Session 默认是不共享的,因为 Cookie 名称为 JSESSIONID 的 Cookie 根域是默认是没设置的,访问不同的二级域名,其 Cookie 就重新生成,而 session 就是根据这个 Cookie 来生成的,所以在不同的二级域名下生成的 Session 也不一样。
    找到了其原因,就可根据这个原因对 Tomcat 在生成 Session 时进行相应的修改。

    快速解决方案1
    在项目的/MET-INF/ 目录下创建一个 context.xml 文件,内容为:

    1 2
    <?xml version="1.0" encoding="UTF-8"?> <Context useHttpOnly="true" sessionCookiePath="/"sessionCookieDomain=".XXXX.com" />

    Done!

    快速解决方案2:修改 Tomcat 的 server.xml 文件,内容为:

    1
    <Context path="" docBase="ROOT" reloadable="false" useHttpOnly="true"sessionCookiePath="/" sessionCookieDomain=".XXXX.com" />

    Done!

    以上两种方案的详细讲解见:http://tomcat.apache.org/tomcat-6.0-doc/config/context.html

    快速解决方案3
    :生成一个叫做 crossSubdomainSessionValve.jar 的文件,用的时候放在 Tomcat lib 目录下,然后修改 Tomcat server.xml 文件:

    1
    <Valve className="me.seanchang.CrossSubdomainSessionValve" />



    原理:取代由 Tomcat 域产生的会话 cookie ,允许该会话 cookie 跨子域共享。

     

     

    测试发现,JSESSIONID不能共享,但cookie可以共享...

    后来使用tomcat7版本测试,cookie可以共享,另外发现SESSIONID可以共享。但session中的其他内容不能共享。

    ------------------------------------------other end--------------------------------------------------------

     方案五:

     经过最后, 通过配置tomcat7,和开发时小改动,成功达到共享session的方案如下:
    (不过终极方案还是缓存+session管理接口实现)

     

    同一个tomcat多个web应用共享session

    tomcat版本:apache-tomcat-6.0.29(次方tomcat6和tomcat7支持)

     

    1.修改D:apache-tomcat-6.0.29confserver.xml文件

     


    由于每个app都有一个唯一的一个ServletContext 实例对象,下面的所有的servlet 共享此ServletContext。
    利用ServletContext 中的setAttribute() 方法把Session 传递过去 然后在另外一个app中拿到session实例。


    设置为true 说明你可以调用另外一个WEB应用程序 通过ServletContext.getContext() 获得ServletContext ;
    然后再调用其getattribute() 得到你要的对象。

     

     

     

    2.创建两个web项目

    两个项目访问URL为:

            http://localhost:8080/app1/

            http://localhost:8080/app2/

     

    app1的index.jsp代码如下:

    app2的index.jsp代码如下:

    3.访问项目:

     

    4.原理(个人浅见)

    全局只用app1的session!

    app1使用session时,直接使用;其他app使用session的时候通过application获取app1的session,然后使用。

    当浏览器关闭,app1的session也就关闭。application的globalSession的value为null。


    获取application

    application为jsp的九大内置对象,在jsp里面可以直接使用。在servlet或者struts2的action里面可以通过request.getSession.getServletContext()获取!

     

    APP1的角色

    一般app1扮演“首页”角色,初始化。后面的项目使用其session。

     

     

     设置crossContext = true,让两个应用可以在tomcat中交叉使用上下文环境

     

    ------------------------------------------------------------

    /////////////////////////////////////////////////////////////////////////////////////////

    最后,还是得采用基于缓存(Memcache/redis)的Session共享的方式才能实现,以上实现大都不能解决session里的数据共享。
    redis实现如下:
    tomcat-redis-session-manager.jar的下载地址https://github.com/jcoleman/tomcat-redis-session-manager.git。 放到tomcat的lib目录下(注意此jar依赖的jar也要放到tomcat的lib下)。

     修改tomcat6的server.xml文件如下: 
              
       <Host name="s1.test.com"  appBase="d:/w33"
                unpackWARs="true" autoDeploy="true"
                xmlValidation="false" xmlNamespaceAware="false">
         
       <Context docBase="D:/bak/apache-tomcat-6.0.37/webapps/sso1" path=""  sessionCookiePath="/" sessionCookieDomain=".test.com" sessionCookieName="JSESSIONID" useHttpOnly="true" privileged="true" >
       
       <Valve className="com.radiadesign.catalina.session.RedisSessionHandlerValve" />
         
       <Manager className="com.radiadesign.catalina.session.RedisSessionManager"
         host="172.22.203.115"
         port="6379" 
         database="0" 
         maxInactiveInterval="60"/>
       
       </Context>

          </Host>
       
        <Host name="s2.test.com"  appBase="d:/w33"
                unpackWARs="true" autoDeploy="true"
                xmlValidation="false" xmlNamespaceAware="false">

        <Context docBase="D:/bak/apache-tomcat-6.0.37/webapps/sso2" path=""  sessionCookiePath="/" sessionCookieDomain=".test.com" sessionCookieName="JSESSIONID" useHttpOnly="true" privileged="true" >

       <Valve className="com.radiadesign.catalina.session.RedisSessionHandlerValve" />
         
       <Manager className="com.radiadesign.catalina.session.RedisSessionManager"
         host="172.22.203.115"
         port="6379" 
         database="0" 
         maxInactiveInterval="60"/>
         
        </Context>
       
        </Host>

     

  • 相关阅读:
    select 1
    使用Word2016发布CSDN博客
    使用word 2013 发布csdn博客
    使用word写CSDN博客文章
    用Word 写csdn blog
    如何使用office2016发布CSDN博客
    用word发CSDN blog
    使用word文档直接发表博客 8 )
    将Word发布到博客园
    Word 2010发布博客文章(修正)
  • 原文地址:https://www.cnblogs.com/mrcharles/p/11879854.html
Copyright © 2020-2023  润新知