在实际应用中,可能需要在多个应用中共享Session数据,例如实现单点登录等。同域中的应用若需实现共享Session,则需要在Server.xml中配置如下属性:
base-context:应用的基础上下文,需要共享session的应用设置相同的base-context。
global-session:是否为全局session,此处应设为true。在此举例说明:
配置两个应用test1,test2共享session
1.配置server.xml使用相同的base-context,设置global-session为true,具体配置如下:
<application name="test1" base="applications/test1" base-context="/test" global-session="true" start="auto"/> <application name="test2" base="applications/test2" base-context="/test" global-session="true" start="auto"/>
2.设置每一个应用里面的apusic-application.xml,增加context-root 的属性配置,如果没有配置,则使用base-context,会导致contextroot冲突。如上面的例子。
test1的配置:
<apusic-application> <module uri=""> <web> <context-root>/</context-root> </web> </module> </apusic-application>
test2的配置:
<apusic-application> <module uri=""> <web> <context-root>/test2</context-root> </web> </module> </apusic-application>
3.测试,在test1应用有一个index.jsp页面,设置一个sesion值,然后定向到/test2应用的getsession.jsp页面,并获取test1设置的值,获取成功。
index.jsp页面大致如下:
<% session.setAttribute("test1","你好吗"); System.out.println("access index.jsp..........."); %> <a href="<%=request.getContextPath()%>/test2/getSession.jsp">test2同一个session</a></td>
getsession.jsp页面大致如下:
<% System.out.println("access get Session..........."); out.print("session value:"+session.getAttribute("test1")); %>