同一个tomcat的webapps之间的共享对象

我有2个webapps在两个上下文中运行:c1,c2(都在根之后)。 我把一个startupListener放在c1中共享一个变量,另一个放在c2中来检索它。

我在c1中的startuplistener是:

public void contextInitialized(ServletContextEvent sce) { HashMap  database ; //some code to init database ServletContext context = sce.getServletContext().getContext("/c1"); if (context!=null) { context.setAttribute("crossContext", true); context.setAttribute("cache", database); } } 

在c2应用程序中,它是这样的:

  public void contextInitialized(ServletContextEvent sce) { ServletContext context = sce.getServletContext().getContext("/c1"); HashMap database = (HashMap) context.getAttribute("cache"); } 

c2的startupListener中的上下文总是为null,我试过’/ c1’,’c1’。 我错过了什么? (我正在使用tomcat6,如果重要的话)谢谢

您需要设置crossContext = true。 来自tomcat文档:

如果希望在此应用程序中调用ServletContext.getContext()以成功返回在此虚拟主机上运行的其他Web应用程序的请求调度程序,则设置为true。 在安全意识环境中设置为false(默认值),以使getContext()始终返回null。

http://tomcat.apache.org/tomcat-7.0-doc/config/context.html

问题:

应用初始化不匹配可能是app1在app1之前初始化。

有一个潜在的“解决方法”:如果您实际上有两个(或更多)应用程序相互依赖,您可能决定在server.xml:启动多个服务server.xml:

     ...        ...    

还有一个选择是使用序列化。 在一个应用程序中序列化数据并在另一个应用程序中读取相同的数据。