Tomcat中两个不同项目共享Session
本文研究的是同一個(gè)Tomcat目錄下的兩個(gè)不同的應(yīng)用共享同一個(gè)session。由于每個(gè)WEB應(yīng)用程序都有一個(gè)唯一的一個(gè)ServletContext實(shí)例對(duì)象,本應(yīng)用中的所有的servlet共享此ServletContext。利用ServletContext中的setAttribute()方法把Session傳遞過(guò)去 然后在另外一個(gè)WEB程序中拿到session實(shí)例。
一、修改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.
設(shè)置為true說(shuō)明可以調(diào)用另外一個(gè)WEB應(yīng)用程序,通過(guò)ServletContext.getContext() 獲得ServletContext然后再調(diào)用其getattribute()得到對(duì)象。
二、在項(xiàng)目A中,寫入以下代碼:
項(xiàng)目A為/projectA
項(xiàng)目B為/projectB
項(xiàng)目A中設(shè)置Session:
HttpSession session = req.getSession();
session.setAttribute("name", "Tom");
session.setMaxInactiveInterval(6565);
ServletContext ContextA =req.getSession().getServletContext();
ContextA.setAttribute("session", req.getSession());
項(xiàng)目B中取出Session:
HttpSession session1 =req .getSession(); ?
ServletContext Context = session1.getServletContext(); ?
ServletContext Context1= Context.getContext("/myweb"); // 項(xiàng)目A的虛擬路徑
HttpSession session2 =(HttpSession)Context1.getAttribute("session");
System.out.println("base傳過(guò)來(lái)的user為:"+session2.getAttribute("name"));
原帖地址:http://www.codesky.net/article/201104/174499.html
轉(zhuǎn)載于:https://blog.51cto.com/woshixy/1352578
總結(jié)
以上是生活随笔為你收集整理的Tomcat中两个不同项目共享Session的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: HTML5 跨文档消息传输
- 下一篇: 【堆栈】最近有兴趣的几个问题