Tomcat多应用共享Session

1. 新建两个应用:

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中交叉使用上下文环境。

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

  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值