http://my.oschina.net/huangcongcong/blog/521025
有时我们会遇到一个大点的项目,为了方便实现有些功能,我们会把项目拆成不同的独立web项目。
但我们在管理这些项目时,只有一个登陆口,然后在其他项目取session来实现身份的验证。
查看tomcat 关于 HTTP Connector 中有个emptySessionPath 其解释如下:
If set to true, all paths for session cookies will be set to /. This can be useful for portlet specification implementations. If not specified, this attribute is set to false.
A side effect to setting this to true, is that if Tomcat creates a new session it will attempt to use the cookie session id if supplied by the client.
所以的需要一个tomcat下两个WEB之间通过session 共享数据
由于每个WEB应用程序都有一个唯一的一个ServletContext 实例对象,自己下面的所有的servlet 共享此ServletContext。
利用ServletContext 中的setAttribute() 方法把Session传递过去 然后在另外一个WEB程序中拿到session实例。
1: 修改Tomcat---conf----server.xml文件
<Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true" xmlNamespaceAware="false" x mlValidation="false"></Host>
修改为:
<Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true" xmlNamespaceAware="false" x mlValidation="false">
<Context path="/项目A" reloadable="false" crossContext="true"></Context>
<Context path="/项目B" 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() 得到你要的对象.