Tomcat多应用共享Session

来源:互联网 发布:it桔子 类似网站 编辑:程序博客网 时间:2024/05/17 03:57

1. 新建两个应用:

test1

    |------WEB-INF

    |              |------web.xml

    |------test.jsp


test.jsp代码

[java] view plaincopy
  1. <%  
  2.     session.setAttribute("test1Session","test1Session");  
  3.     session.getServletContext().setAttribute("t1_session",session);  
  4.     out.println("Application /test1 is ok!<br>");  
  5.       
  6.     if(session.getServletContext().getContext("/test2")!=null){  
  7.         HttpSession t2_session = (HttpSession)session.getServletContext().getContext("/test2").getAttribute("t2_session");  
  8.         if(t2_session!=null){  
  9.             String str = (String)t2_session.getAttribute("test2Session");  
  10.             String path = request.getContextPath();  
  11.             out.println("Application "+path +":"+str+"<br>");  
  12.         }else{  
  13.             out.println("Application /test2 no data!");  
  14.         }  
  15.     }  
  16. %>  


test2

    |------WEB-INF

    |              |------web.xml

    |------test.jsp


test.jsp代码

[java] view plaincopy
  1. <%  
  2.     session.setAttribute("test2Session","test2Session");  
  3.     session.getServletContext().setAttribute("t2_session",session);  
  4.     out.println("Application /test2 is ok!<br>");  
  5.       
  6.     if(session.getServletContext().getContext("/test1")!=null){  
  7.         HttpSession t1_session = (HttpSession)session.getServletContext().getContext("/test1").getAttribute("t1_session");  
  8.         if(t1_session!=null){  
  9.             String str = (String)t1_session.getAttribute("test1Session");  
  10.             String path = request.getContextPath();  
  11.             out.println("Application "+path +":"+str+"<br>");  
  12.         }else{  
  13.             out.println("Application /test1 no data!");  
  14.         }  
  15.     }  
  16. %>  


2. 配置tomcat,设置crossContext = true,让两个应用可以在tomcat中交叉使用上下文环境。

<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中的数据。

0 0
原创粉丝点击