Show TOC

Composing HTTP ResponsesLocate this document in the navigation structure

Procedure

To compose an HTTP response in your servlet you have to take care of two basic things:

  1. Write the HTTP response header fields.

    Remember that you have to write the HTTP response headers before you start writing content to the response object, or at least before the response stream is flushed.

    To set headers of the response message, you can use the following methods of the ServletResponse object - setHeader(String name, String value) , setDateHeader(String name, long date) , or setIntHeader(String name, int value) . If you try to write a header that already exists, the previous value of the header is replaced with the current one. To prevent this, you can check whether a header is set using the containsHeader() method.

    The following methods are often used when constructing responses:

    To insert

    Use

    The content type of the response

    response.setContentType(String type) method. An example of such a type is "text/html" for HTML pages.

    The length of the response body

    response.setContentLength(int len) method.

    Note

    If you do not flush the output stream and the response length does not exceed the size of the buffer, it is not necessary to use this method.

  2. Write the response message body

    You can use either the PrintWriter , or the OutputStream to generate the response. If you use OutputStream , the response body will be sent as binary data. The PrintWriter sends character text responses to the client.

    • To get the PrintWriter , use the PrintWriter out = res.getWriter(); method.

    • To get the output stream, use the ServletOutputStream out = res.getOutputStream(); method.

Caution

If you want to use a persistent connection for the response, do not use the flush() method of the output stream.

Note

You cannot use both the PrintWriter and the ServletOutputStream in the same request-response cycle.

Example

Generating an HTML Page

Sample Code
                  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
    // Set the Content-Type header
    response.setContentType("text/html");
    // Get the writer object
    PrintWriter out = response.getWriter();
    out.println(
               "<HTML>\n" +
               "<HEAD><TITLE>Hello WWW</TITLE></HEAD>\n" +
               "<BODY>\n" +
               "<H1>First HTML Servlet</H1>\n" +
               "</BODY></HTML>");
  }
}

               

Returning an Image

Sample Code
                  // This method is called by the servlet container to process a GET request.
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // Get the absolute path of the image
        ServletContext sc = getServletContext();
        String filename = sc.getRealPath("image.gif");
    
        // Get the MIME type of the image
        String mimeType = sc.getMimeType(filename);
        if (mimeType == null) {
            sc.log("Could not get MIME type of "+filename);
               resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }
    
        // Set content type
        resp.setContentType(mimeType);
    
        // Set content length
        File file = new File(filename);
        resp.setContentLength((int)file.length());
    
        // Open the file and output streams
        FileInputStream in = new FileInputStream(file);
        OutputStream out = resp.getOutputStream();
    
        // Copy the contents of the file to the output stream
        byte[] buf = new byte[1024];
        int count = 0;
        while ((count = in.read(buf)) >= 0) {
            out.write(buf, 0, count);
        }
        in.close();
        out.close();
    }