Tomcat中两个不同项目共享Session

分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow

也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!

               

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

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

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

修改为:

<Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true" xmlNamespaceAware="false" mlValidation="false">
 <Context path="/projectA" reloadable="false" crossContext="true"></Context>
 <Context path="/projectB" 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()得到对象。
 

扫描二维码关注公众号,回复: 4080038 查看本文章

二、在项目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

           

给我老师的人工智能教程打call!http://blog.csdn.net/jiangjunshow

这里写图片描述

猜你喜欢

转载自blog.csdn.net/hdsghtj/article/details/84099413