java session 跨项目_[Java教程]tomcat session共享: 同tomcat不同项目之间的session共享

注意 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下不同项目之间共享sessionJava代码

bc91bb04e6e9c61e24c974e4440db8f2.gif 

bc91bb04e6e9c61e24c974e4440db8f2.gif

bc91bb04e6e9c61e24c974e4440db8f2.gifHttpSession session = req.getSession();

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

session.setMaxInactiveInterval(6565);

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

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

HttpSession session = req.getSession(); session.setAttribute("name", "xbkaishui"); session.setMaxInactiveInterval(6565); ServletContext ContextA =req.getSession().getServletContext(); ContextA.setAttribute("session", req.getSession());

//测试Java代码

bc91bb04e6e9c61e24c974e4440db8f2.gif 

bc91bb04e6e9c61e24c974e4440db8f2.gif

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

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

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

bc91bb04e6e9c61e24c974e4440db8f2.gif 

bc91bb04e6e9c61e24c974e4440db8f2.gif

bc91bb04e6e9c61e24c974e4440db8f2.gifHttpSession 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"));

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"));

然后重新部署就行了。  本文网址:http://www.shaoqun.com/a/151810.html

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:admin@shaoqun.com。

tomcat

0

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值