Shaping Servlet Responses

Available

3.1 HttpServletResponse class

After calling service()your servlet method, the web container will generate a response to the client based on the HttpServletResponse. So if you want to somehow influence the response to the client, then you should modify this object.

The server response consists of three parts:

  • Status line (for example: 200 OK)
  • Headers
  • Response body

And class methods HttpServletResponseare also divided into 3 groups? Almost:

Methods Description
1 void setStatus(int sc) Sets the response status code.
2 void sendError(int sc) Sends an error to the client with the specified code.
3 void sendError(int sc, String msg) Sends an error with the specified code and a message to the client.
4 void addHeader(String name, String value) Adds a header to the list of response headers.
5 void setHeader(String name, String value) Changes the header in the list of response headers.
6 boolean containsHeader(String name) Checks if the header already exists.
7 void addCookie(Cookie cookie) Adds a Cookie to the response.
8 void sendRedirect(String location) Redirects the client to a different URL.
9 String encodeRedirectURL(String url) Encodes the specified URL for use in the sendRedirect method.
10 String encodeURL(String url) Encodes the specified URL, including the session ID.
eleven void setContentType(String type) Sets the MimeType of the result.
12 void setContentLength(int len) Sets the length of the response body.
13 void setCharacterEncoding(String charset) Sets the response encoding set.
14 void setBufferSize(int size) Sets the buffer size for the response body.
15 boolean isCommitted() Checks if the buffer has already been written to the response.
16 void flushBuffer() Writes the contents of the buffer to the response.
17 void reset() Resets all data that is stored in the buffer, headers and response codes.
18 void resetBuffer() Clears the response buffer.

The methods here are quite trivial. But I'll give you a few highlights below.

Buffer . Your servlet's response is written to a buffer, not immediately sent to the user. Therefore, at some stage (if, for example, an error occurs), you can reset (erase) everything that is written to the buffer. You can even call the reset() method and erase not only the contents of the buffer, but also the headers with the response code.

3.2 redirect()

The second important point is the redirect. If your servlet decides to redirect the client to another URL, then you need to somehow send this URL to the client. This can be done using the sendRedirect.

But there is an important nuance. The URI can contain a wider range of characters than allowed in the response body. Therefore, the URL must first be encoded into a valid character set before calling the method sendRedirect(). There is a special method for this encodeRedirectURL(String url). Use it.

Redirect example:

public class RedirectServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String newUrl = "http://google.com?q=Learn to google!";
        String redirectUrl = response.encodeRedirectURL(newUrl);
        response.sendRedirect(redirectUrl);
    }
}

3.3 getWriter() method

And now we will learn how to write our text as a response body. To do this, the class HttpServletResponsehas a special method getWriter()that returns an object PrintStream. If anyone forgot, this is the type of field with the name System.out.

In order to write some text as a servlet response, you need:

  • Get the PrintStream object by calling the response.getWriter().
  • Write whatever you think is necessary to the PrintStream object (all data will be written to the buffer).
  • Send the buffer to the user by calling the method close()on the PrintStream.

Let's write a servlet that adds two numbers aand breturns the result to the user:

public class CalculatorServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws Exception {
         // Getting the parameter “a” and “b” from request
        String a = request.getParameter("a");
        String b = request.getParameter("b");

        try {
            // Convert strings to numbers and calculate sum
            int sum = Integer.parseInt(a) + Integer.parseInt(b);

            // Print HTML as a response for browser
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();

            out.println("<html>");
            out.println("<head> <title> CalculatorServlet </title> </head>");
            out.println("<body>");
            out.println("<h1> Sum == " + sum + "</h1>");
            out.println("</body>");
            out.println("</html>");
        } finally {
            out.close();
        }
    }
}
Comments (1)
  • Popular
  • New
  • Old
You must be signed in to leave a comment
Thomas
Level 41 , Bayreuth, Germany
15 March, 12:34
getWriter() returns a PrintWriter and not a PrintStream (it's correct in the example though)