Tomcat配置多應用共享Session(使用crossContext)
test1
|------WEB-INF
| |------web.xml
|------test.jsp
test.jsp程式碼
- <%
- session.setAttribute("test1Session","test1Session");
- session.getServletContext().setAttribute("t1_session",session);
- out.println("Application /test1 is ok!<br>");
- if(session.getServletContext().getContext(
"/test2")!=null){- HttpSession t2_session = (HttpSession)session.getServletContext().getContext("/test2").getAttribute("t2_session");
- if(t2_session!=null){
- String str = (String)t2_session.getAttribute("test2Session");
- String path = request.getContextPath();
- out.println("Application "+path +":"+str+"<br>");
- }else{
- out.println("Application /test2 no data!");
- }
- }
- %>
test2
|------WEB-INF
| |------web.xml
|------test.jsp
test.jsp程式碼
- <%
- session.setAttribute("test2Session"
,"test2Session");- session.getServletContext().setAttribute("t2_session",session);
- out.println("Application /test2 is ok!<br>");
- if(session.getServletContext().getContext("/test1")!=null){
- HttpSession t1_session = (HttpSession)session.getServletContext().getContext("/test1").getAttribute("t1_session");
- if(t1_session!=null){
- String str = (String)t1_session.getAttribute("test1Session");
- String path = request.getContextPath();
- out.println("Application "+path +":"+str+"<br>");
- }else{
- out.println("Application /test1 no data!");
- }
- }
- %>
2. 配置tomcat,設定crossContext = true,讓兩個應用可以在tomcat中交叉使用上下文環境。
在<Host></Host>結點中新增:
<Context path="/test1" docBase="C:/test1" reloadable="true" crossContext="true"></Context>
<Context path="/test2" docBase="C:/test2" reloadable="true" crossContext="true"></Context>
3. 啟動Tomcat,訪問http://localhost:8080/test1/test.jsp
頁面輸出:Application /test1 is ok!------------------------test1儲存session成功
Application /test2 no data!--------------------test2還沒有被訪問,所以test2的session中沒有資料訪問http://localhost:8080/test2/test.jsp
頁面輸出:Application /test2 is ok!------------------------test2儲存session成功
Application /test2:test1Session-------------test1Session來自test1應用中session重新整理http://localhost:8080/test1/test.jsp
頁面輸出:Application /test1 is ok!------------------------test1儲存session成功
Application /test1:test2Session-------------test2Session來自test2應用中session
應用test1和test2成功共享session,可以互相訪問另一個應用中的session和session中的資料。