同一tomcat下多项目Session共享

参考的是这里的文章
之前做Session共享一直是用reids+SpringSeesion做。这次做公司管理后台比较小的项目想直接用修改server.xml的方式来做到seesion共享

但是代码修改完成后遇到以下问题:
  • 前提:B项目依赖A项目的身份验证
  • B项目获取的session存的是A项目最后一个登录人的信息
  • A项目只要在任何一个浏览器登录,B项目在其他浏览器可以通过身份验证直接访问
以下是原有项目代码
<Host name="localhost"  appBase="webapps"unpackWARs="true" autoDeploy="true">
    <Context path="/WebappA"  debug="9" reloadable="true" crossContext="true"/> 
    <Context path="/WebappB"  debug="9" reloadable="true" crossContext="true"/>
</Host>

WebappA:

HttpSession session = request.getSession();
session.setAttribute("userId", "test");
ServletContext ContextA =session .getServletContext();
ContextA.setAttribute("session", session ); //注意:这里传递的key为seesion

WebappB:

HttpSession sessionB = request.getSession();  
ServletContext ContextB = sessionB.getServletContext();  
ServletContext ContextA= ContextB.getContext("/WebappA");
HttpSession sessionA =(HttpSession)ContextA.getAttribute("session");
System.out.println("userId: "+sessionA.getAttribute("userId"));
修改之后的项目代码

增加了sessionCookiePath="/" 在同一ip端口下的应用可以访问session,cookie

<Host name="localhost"  appBase="webapps"unpackWARs="true" autoDeploy="true">
    <Context path="/WebappA"  debug="9" reloadable="true" crossContext="true"  sessionCookiePath="/" /> 
    <Context path="/WebappB"  debug="9" reloadable="true" crossContext="true"  sessionCookiePath="/ "/>
</Host>

WebappA:

HttpSession session = request.getSession();
session.setAttribute("userId", "test");
ServletContext ContextA =session .getServletContext();
ContextA.setAttribute(session.getId(), session ); //注意:这里传递的key为seesionId

WebappB:

HttpSession sessionB = request.getSession();  
ServletContext ContextB = sessionB.getServletContext();  
ServletContext ContextA= ContextB.getContext("/WebappA");
HttpSession sessionA =(HttpSession)ContextA.getAttribute(sessionB .getId()); //注意:这里是拿seesionId获取session
System.out.println("userId: "+sessionA.getAttribute("userId"));

至此以上问题就消除了。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值