zoukankan      html  css  js  c++  java
  • 同一个Tomcat不同Web应用之间共享会话Session

    查看tomcat 关于 HTTP Connector 中有个emptySessionPath 其解释如下:

    If set to true, all paths for session cookies will be set to /. This can be useful for portlet specification implementations. If not specified, this attribute is set to false.
    A side effect to setting this to true, is that if Tomcat creates a new session it will attempt to use the cookie session id if supplied by the client.

    设置为true 发现没有用 在网上搜了一下方法 基本是这样的:

    由于每个WEB应用程序都有一个唯一的一个ServletContext 实例对象,自己下面的所有的servlet 共享此ServletContext

    利用ServletContext 中的setAttribute() 方法把Session 传递过去 然后在另外一个WEB程序中拿到session实例。

    1: 修改Tomcat---conf----server.xml文件

         把 <Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true" xmlNamespaceAware="false" x  mlValidation="false"></Host> 修改为:


    <Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true" xmlNamespaceAware="false" x  mlValidation="false">

    <Context data-path="/项目A" reloadable="false" crossContext="true"></Context> 
          <Context data-path="/项目B" reloadable="false" crossContext="true"></Context>

    </Host>

    注意 crossContext 属性在帮助文档中意思

    crossContext: Set to true if you want calls within this application to ServletContext.getContext() to successfully return a request dispatcher for other web applications running on this virtual host. Set to false (the default) in security conscious environments, to make getContext() always return null.

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

    2:  在项目A中,写入以下代码:

    我们假定 项目A 为/myweb

      项目B为 /w2


    //以下内容用于测试同一tomcat下不同项目之间共享session 
        HttpSession session = req.getSession();

    session.setAttribute("name", "xbkaishui");

    session.setMaxInactiveInterval(6565);

      ServletContext ContextA =req.getSession().getServletContext();

      ContextA.setAttribute("session", req.getSession());

    //测试

    out.println("IN SessionRangleServlet name : "+session.getAttribute("name"));

    3.在项目B中,写入以下代码取出Session

    HttpSession session1 =req .getSession();  

            ServletContext Context = session1.getServletContext();  

    // 这里面传递的是项目a的虚拟路径

            ServletContext Context1= Context.getContext("/myweb");

             System.out.println(Context1);

            HttpSession session2 =(HttpSession)Context1.getAttribute("session");

            System.out.println("base传过来的user为:"+session2.getAttribute("name"));

    然后重新部署就行了。

  • 相关阅读:
    c#中using System.Runtime.Serialization.Json;不能引用
    VS2013 当前不会命中断点还未为文档加载任何符号
    windows2008 设置会话超时时间
    服务没有及时响应启动或控制请求 1053
    IIS装好了无法访问localhost
    Shiro笔记——简介、 架构分析
    Java 连接使用 Redis
    Java 连接操作 Redis 出现错误
    网络方面的常用命令 & 常用端口介绍
    Redis 配置文件及命令详解
  • 原文地址:https://www.cnblogs.com/songyanlei/p/2975497.html
Copyright © 2011-2022 走看看