CrossContext and RequestDispatcher in webapps

This article will describe how to use a crosscontext requestdispatcher to communicate between two servlets in different webapps.

Settings the example

Lets say you have two webapps loaded in tomcat:

  • CustomerPortal (loaded at http://myserver.com/CustomerPortal)
  • EmployeePortal (loaded at http://myserver.com/EmployeePortal)

In the CustomerPortal you want to be able to show an Employee Datasheet by calling:

http://myserver.com/EmployeePortal/employee?id=<employeeid>

and in the EmployeePortal you want to show a Customer Datasheet by calling:

http://myserver.com/CustomerPortal/customer?id=<customerid>

 

Allowing the communication with CrossContext

For each project, add a file named context.xml to the META-INF library that contains the following:

<Context crossContext="true" />

If your webapp already has a context.xml file, just add the crossContext parameter to the context-tag.

Now you have allowed the webapps to communicate. Next step is to do the actual communication.

Perform communication with RequestDispatcher

For doing the communication, we need a RequestDispatcher.

ServletContext sc = this.getServletContext().getContext("/CustomerPortal");
RequestDispatcher disp = s1.getRequestDispatcher("customer?id=" + customerId);               
                
try {
    disp.include(request, response);
}  
catch(Exception e) {
    e.printStackTrace();
}

The above code will call CustomerPortal/customer?id=xxx and include the code received in the current spot of the page. The example is easily changed for calling the EmployeePortal.

Handle the response

In case you want it to be a bit more flexible and handle the response, the following code can be used instead

ServletContext sc = this.getServletContext().getContext("/CustomerPortal");
RequestDispatcher disp = s1.getRequestDispatcher("customer?id=" + customerId); 
StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw);
HttpServletResponse responseWrapper =
    new HttpServletResponseWrapper(response) {
        @Override
        public PrintWriter getWriter() throws IOException {
            return pw;
        }
    };
dispatcher.include(request, responseWrapper);
System.out.println("html from customerportal: " + sw.toString());

Leave a Reply

Your email address will not be published. Required fields are marked *