Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shared objects between webapps of the same tomcat

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

like image 811
EyeQ Tech Avatar asked Mar 14 '13 08:03

EyeQ Tech


1 Answers

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

like image 71
Brad at Kademi Avatar answered Oct 11 '22 12:10

Brad at Kademi