The Java EE 5 Tutorial

Including Other Resources in the Response

It is often useful to include another web resource (for example, banner content or copyright information) in the response returned from a web component. To include another resource, invoke the include method of a RequestDispatcher object:

include(request, response);

If the resource is static, the include method enables programmatic server-side includes. If the resource is a web component, the effect of the method is to send the request to the included web component, execute the web component, and then include the result of the execution in the response from the containing servlet. An included web component has access to the request object, but it is limited in what it can do with the response object:

The banner for the Duke’s Bookstore application is generated by BannerServlet. Note that both doGet and doPost are implemented because BannerServlet can be dispatched from either method in a calling servlet.

public class BannerServlet extends HttpServlet {
     public void doGet (HttpServletRequest request,
        HttpServletResponse response)
        throws ServletException, IOException {
            output(request, response);
    }
    public void doPost (HttpServletRequest request,
        HttpServletResponse response)
        throws ServletException, IOException {
            output(request, response);
}

private void output(HttpServletRequest request,
        HttpServletResponse response)
        throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        out.println("<body bgcolor=\"#ffffff\">" +
        "<center>" + "<hr> <br> &nbsp;" + "<h1>" +
        "<font size=\"+3\" color=\"#CC0066\">Duke’s </font>" +
        <img src=\"" + request.getContextPath() +
        "/duke.books.gif\">" +
         "<font size=\"+3\" color=\"black\">Bookstore</font>" +
        "</h1>" + "</center>" + "<br> &nbsp; <hr> <br> ");
    }
}

Each servlet in the Duke’s Bookstore application includes the result from BannerServlet using the following code:

RequestDispatcher dispatcher =
    getServletContext().getRequestDispatcher("/banner");
if (dispatcher != null)
    dispatcher.include(request, response);
}