background image

HttpServlet Class

<< Invoking OtherWeb Resources | Transferring Control to Another Web Component >>
<< Invoking OtherWeb Resources | Transferring Control to Another Web Component >>

HttpServlet Class

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 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);
}
Invoking Other Web Resources
Chapter 4 · Java Servlet Technology
123