10.12.2012 Views

The Java EE 5 Tutorial (PDF) - Oracle Software Downloads

The Java EE 5 Tutorial (PDF) - Oracle Software Downloads

The Java EE 5 Tutorial (PDF) - Oracle Software Downloads

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

If the resource is static, the include method enables programmatic server-side includes. If the<br />

resource is a web component, the effect of the method is to send the request to the included web<br />

component, execute the web component, and then include the result of the execution in the<br />

response from the containing servlet. An included web component has access to the request<br />

object, but it is limited in what it can do with the response object:<br />

■ It can write to the body of the response and commit a response.<br />

■ It cannot set headers or call any method (for example, setCookie) that affects the headers of<br />

the response.<br />

<strong>The</strong> banner for the Duke’s Bookstore application is generated by BannerServlet. Note that<br />

both doGet and doPost are implemented because BannerServlet can be dispatched from either<br />

method in a calling servlet.<br />

public class BannerServlet extends HttpServlet {<br />

public void doGet (HttpServletRequest request,<br />

HttpServletResponse response)<br />

throws ServletException, IOException {<br />

output(request, response);<br />

}<br />

public void doPost (HttpServletRequest request,<br />

HttpServletResponse response)<br />

throws ServletException, IOException {<br />

output(request, response);<br />

}<br />

private void output(HttpServletRequest request,<br />

HttpServletResponse response)<br />

throws ServletException, IOException {<br />

PrintWriter out = response.getWriter();<br />

out.println("" +<br />

"" + " &nbsp;" + "" +<br />

"Duke’s " +<br />

" +<br />

"Bookstore" +<br />

"" + "" + " &nbsp; ");<br />

}<br />

}<br />

Each servlet in the Duke’s Bookstore application includes the result from BannerServlet using<br />

the following code:<br />

RequestDispatcher dispatcher =<br />

getServletContext().getRequestDispatcher("/banner");<br />

if (dispatcher != null)<br />

dispatcher.include(request, response);<br />

}<br />

Invoking OtherWeb Resources<br />

Chapter 4 • <strong>Java</strong> ServletTechnology 123

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!