5

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

EyeQ Tech
  • 7,198
  • 18
  • 72
  • 126

3 Answers3

3

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

Brad at Kademi
  • 1,300
  • 8
  • 7
  • Also see this question http://stackoverflow.com/questions/661978/what-does-the-crosscontext-attribute-do-in-tomcat-does-it-enable-session-sharin – Brad at Kademi Mar 14 '13 at 20:54
  • hey Brad, I did set crossContext to true in app c1. – EyeQ Tech Mar 15 '13 at 01:24
  • if it's helpful to s/o else: Brad's answer is correct, but note the crossContext=true is set in the config/context.xml of your tomcat folder. – EyeQ Tech Mar 15 '13 at 06:32
0

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>
Rais Alam
  • 6,970
  • 12
  • 53
  • 84
-1

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

Sudhanshu Umalkar
  • 4,174
  • 1
  • 23
  • 33