Servlet Responses

In order to do anything useful, a servlet must send a response to each request that is made to it. In the case of an HTTP servlet, the response can include three components: a status code, any number of HTTP headers, and a response body.

The ServletResponse and HttpServletResponse interfaces include all the methods needed to create and manipulate a servlet’s output. We’ve already seen that you specify the MIME type for the data returned by a servlet using the setContentType( ) method of the response object passed into the servlet. With an HTTP servlet, the MIME type is generally text/html, although some servlets return binary data: a servlet that loads a GIF file from a database and sends it to the web browser should set a content type of image/gif while a servlet that returns an Adobe Acrobat file should set it to application/pdf.

ServletResponse and HttpServletResponse each define two methods for producing output streams, getOutputStream( ) and getWriter( ). The former returns a ServletOutputStream, which can be used for textual or binary data. The latter returns a java.io.PrintWriter object, which is used only for textual output. The getWriter( ) method examines the content-type to determine which charset to use, so setContentType( ) should be called before getWriter( ).

HttpServletResponse also includes a number of methods for handling HTTP responses. Most of these allow you to manipulate the HTTP header fields. For example, setHeader( ) ...

Get Java Enterprise in a Nutshell, Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.