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 theinclude 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:
- It can write to the body of the response and commit a response.
- It cannot set headers or call any method (for example,
setCookie) that affects the headers of the response.
The banner for the Duke’s Bookstore application is generated by BannerServlet. Note that both the doGet and doPost methods 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 {
PrintWriter out = response.getWriter();
out.println("<body bgcolor=\"#ffffff\">" +
"<center>" + "<hr> <br> " + "<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> <hr> <br> ");
}
public void doPost (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("<body bgcolor=\"#ffffff\">" +
"<center>" + "<hr> <br> " + "<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> <hr> <br> ");
}
}
Each servlet in the Duke’s Bookstore application includes the result from BannerServlet with the following code:
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/banner"); if (dispatcher != null) dispatcher.include(request, response); }Then Transfer Control to Another Web Component







15 Dec 2011
Posted by Aals 

