How do I obtain ServletContext of another application?

The ServletContext.getContext(String uripath) enable us to access servlet context of another web application deployed on the same application server. A configuration need to be added to enable this feature.

In the example below we will forward the request from the current application to the /otherapp/hello.jsp page. We place a string in the request object attribute of the current application and going to show it in the hello.jsp page.

package org.kodejava.servlet;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = {"/context"})
public class GetAnotherContextServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // Get ServletContext of another application on the same Servlet
        // container. This allows us to forward request to another application
        // on the same application server.
        ServletContext ctx = request.getServletContext().getContext("/otherapp");

        // Set a request attribute and forward to hello.jsp page on another 
        // context.
        request.setAttribute("MESSAGE", "Hello There!");
        RequestDispatcher dispatcher = ctx.getRequestDispatcher("/hello.jsp");
        dispatcher.forward(request, response);
    }
}

To enable this feature in Tomcat we need to enable the crossContext attribute by setting the value to true, the default value is false. Update the server.xml file to add the following configuration inside the <Host> node.

<Context path="/webapp" debug="0" reloadable="true" crossContext="true"/>

Maven dependencies

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
</dependency>

Maven Central

Wayan

2 Comments

  1. Following you example here, would it be possible to get beans from the other applications context?

    Meaning, I have a set of POJOs, and other beans that I would like to share among different applications (WARs), would the retrieved context be able to provide those beans?

    Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.