閱讀819 返回首頁    go 阿裏雲 go 技術社區[雲棲]


Tomcat中兩個不同項目共享Session

本文研究的是同一個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()得到對象。
 

二、在項目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"));


原帖地址:https://www.codesky.net/article/201104/174499.html

最後更新:2017-04-03 12:54:36

  上一篇:go android之service
  下一篇:go LeetCode之K sum problem