shared objects between webapps of the same tomcat

此生再无相见时 提交于 2020-01-03 13:36:46

问题


I have 2 webapps running at two contexts: c1, c2 (both immediately after the root). I put a startupListener in c1 to share a variable, and another one in c2 to retrieve it.

My startuplistener in c1 is:

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

    }

In c2 app, it is like this:

      public void contextInitialized(ServletContextEvent sce) {
            ServletContext context = sce.getServletContext().getContext("/c1");
            HashMap<String,Object> database = (HashMap) context.getAttribute("cache");

      }

The context in the startupListener of c2 is always null, I've tried '/c1', 'c1'. What am I missing? (I'm using tomcat6, if that matters) Thanks


回答1:


You need to set crossContext=true. From the tomcat docs:

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.

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




回答2:


Problem:

There is mismatch in app initialization may be app2 is initialized before app1.

There is a potential "workaround": If you actually have two (or more) apps depending on each other, you may decide to start multiple services in you server.xml:

<Service name="app1">
  <Connector .../>

  <Engine ...>
     <Host appbase="app1" ...>
       ...        
     </Host>
  </Engine>
</Service>
<Service name="app2">
  <Connector .../>

  <Engine ...>
     <Host appbase="app2" ...>
       ...        
     </Host>
  </Engine>
</Service>



回答3:


One more option is use serialization. Serialize the data in one app and read the same in the other one.



来源:https://stackoverflow.com/questions/15404432/shared-objects-between-webapps-of-the-same-tomcat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!