Accessing web application resources from different context

You can access the resources which are available for one servlet context from the other. Let’s say you have two web applications deployed (in the same Servlet container):

Basically, if you’re in /myApp1 and you will execute the getServletContext() method on ServletRequest object, it will return the ServletContext for the application related with this ServletRequest object (in this case – /myApp1).
With the ServletContext object you can execute getResource(-) or getResourceAsStream(-) to get access to the needed resource from within the /myapp1 application.

But what if you would like to get some resource which is available only in /myApp2 context, from the /myApp1 context?

It occurs that there is a way to achieve it, as there is a getContext(String uripath) method in ServletContext object, which allows you to get a ServletContext object related with the uripath passed as a parameter. What’s important, that there is a possibility that your Servlet container is preventing such application cross-access operations because of the security reasons. For example in Tomcat 7 you need to set appropriate attribute (crossContext="true") for <Context> element in TOMCAT_HOME/conf/context.xml file. If you won’t do this, the default value will be “false”.

So, basically what you want is this:

<?xml version='1.0' encoding='utf-8'?>
    <Context crossContext="true">

        <!-- Default set of monitored resources -->

Now assume that you have a file you want to access (and read) from within the /myApp1 application, which is located in /myApp2/WEB-INF/myFile.txt. This how the code could look somewhat like this:

// Without crossAuth="true" in context.xml, Tomcat 7 would return null.
ServletContext ctx = request.getServletContext().getContext("/myApp2");

// Get the resource from different ServletContext
InputStream resource = ctx.getResourceAsStream("/WEB-INF/myFile.txt");

// The main goal is achieved - we have an access to the resource; the rest of
// the code is purely standard InputStream access code - just to see it 
// actually works.
BufferedInputStream bis = new BufferedInputStream(resource);
byte[] b = new byte[100];, 0, 100);

Also notice, that you can obtain the RequestDispatcher either from the ServletRequest or the ServletContext. Hence, you can use the above approach if you would like to dispatch the request for processing to a different application.