您的位置:首页 > 运维架构 > Tomcat

Tomcat中两个不同项目共享Session

2016-06-08 09:22 288 查看
本文研究的是同一个Tomcat目录下的两个不同的应用共享同一个session。由于每个WEB应用程序都有一个唯一的一个ServletContext实例对象,本应用中的所有的servlet共享此ServletContext。利用ServletContext中的setAttribute()方法把Session传递过去
然后在另外一个WEB程序中拿到session实例。

一、修改Tomcat中conf的server.xml文件

 

修改为:

 

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()得到对象。

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

项目A为/projectA

项目B为/projectB

项目A中设置Session:

HttpSession session = req.getSession(); 

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

session.setMaxInactiveInterval(6565);

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

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

项目B中取出Session:

HttpSession session1 =req .getSession();
  

ServletContext Context = session1.getServletContext();
  

ServletContext Context1= Context.getContext("/myweb"); //
项目A的虚拟路径

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

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

原帖地址:http://www.codesky.net/article/201104/174499.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: