HttpResponse Servlet

The HttpServlet class request processing methods take two parameters.

  1. javax.servlet.http.HttpRequest
  2. javax.servlet.http.HttpResponse

The HttpServletResponse object generates a response to return to the requesting client. Its methods allow you to set the response header and the response body.

The first line of the Response header (response.setContentType(“text/html”);) identifies the MIME type of the response. The following three lines are often placed in servlet code to prevent Web browsers and proxy servers from caching dynamically-generated Web pages. If you want your dynamic Web page to be cached, remove these three lines of code.

The response object also has the getWriter() method to return a PrintWriter object. The print() and println() methods of the PrintWriter object write the servlet response back to the client.

For instance, here is the signature of the HttpServlet.doGet() method:

protected void doGet(
    HttpServletRequest request,
    HttpServletResponse response)
      throws ServletException, IOException {

}

 

In this text I will look at the HttpResponse object.

The purpose of the HttpResponse object is to represent the HTTP response your web application sends back to the browser, in response to the HTTP request the browser send to your web application.

Methods to Set HTTP Response Header:

There are following methods which can be used to set HTTP response header in your servlet program. These methods are available with HttpServletResponse object.

1 String encodeRedirectURL(String url)
Encodes the specified URL for use in the sendRedirect method or, if encoding is not needed, returns the URL unchanged.
2 String encodeURL(String url)
Encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL unchanged.
3 boolean containsHeader(String name)
Returns a boolean indicating whether the named response header has already been set.
4 boolean isCommitted()
Returns a boolean indicating if the response has been committed.
5 void addCookie(Cookie cookie)
Adds the specified cookie to the response.
6 void addDateHeader(String name, long date)
Adds a response header with the given name and date-value.
7 void addHeader(String name, String value)
Adds a response header with the given name and value.
8 void addIntHeader(String name, int value)
Adds a response header with the given name and integer value.
9 void flushBuffer()
Forces any content in the buffer to be written to the client.
10 void reset()
Clears any data that exists in the buffer as well as the status code and headers.
11 void resetBuffer()
Clears the content of the underlying buffer in the response without clearing headers or status code.
12 void sendError(int sc)
Sends an error response to the client using the specified status code and clearing the buffer.
13 void sendError(int sc, String msg)
Sends an error response to the client using the specified status.
14 void sendRedirect(String location)
Sends a temporary redirect response to the client using the specified redirect location URL.
15 void setBufferSize(int size)
Sets the preferred buffer size for the body of the response.
16 void setCharacterEncoding(String charset)
Sets the character encoding (MIME charset) of the response being sent to the client, for example, to UTF-8.
17 void setContentLength(int len)
Sets the length of the content body in the response In HTTP servlets, this method sets the HTTP Content-Length header.
18 void setContentType(String type)
Sets the content type of the response being sent to the client, if the response has not been committed yet.
19 void setDateHeader(String name, long date)
Sets a response header with the given name and date-value.
20 void setHeader(String name, String value)
Sets a response header with the given name and value.
21 void setIntHeader(String name, int value)
Sets a response header with the given name and integer value.
22 void setLocale(Locale loc)
Sets the locale of the response, if the response has not been committed yet.
23 void setStatus(int sc)
Sets the status code for this response.

The HttpResponse object has a lot of methods, so I will just cover the most commonly used here. The rest you can read about in the JavaDoc, if you are interested. The parts I will cover are:

  1. Writing HTML
  2. Headers
  3. Content-Type
  4. Writing Text
  5. Content-Length
  6. Writing Binary Data
  7. Redirecting to a Different URL
  8. Writing HTML

To send HTML back to the browser, you have to obtain the a PrintWriter from the HttpResponse object. Here is how:

PrintWriter writer = response.getWriter();
writer.write("<html><body>GET/POST response</body></html>");

Headers

Just like the request object, the HttpRequest can contain HTTP headers. Headers must be set before any data is written to the response. You set a header on the response object like this:

response.setHeader("Header-Name", "Header Value");

As you can see, a response header is a name, value pair.

Content-Type

The Content-Type header is a response header that tells the browser the type of the content you are sending back to it. For instance, the content type for HTML is text/html. Similarly, if what you send back to the browser is plain text, you use the content type text/plain.

Here is how you set the Content-Type header on the HttpResponse object:

response.setHeader("Content-Type", "text/html");

Writing Text

You can write text back to the browser instead of HTML, like this:

response.setHeader("Content-Type", "text/plain");

PrintWriter writer = response.getWriter();
writer.write("This is just plain text");

First the Content-Type header is set to text/plain. Then a plain text string is written to the writer obtained from the response object.

Content-Length

The Content-Length header tells the browser how many bytes your servlet is sending back. If you are sending binary data back you need to set the content length header. Here is how:

response.setHeader("Content-Length", "31642");

Writing Binary Data

You can also write binary data back to the browser instead of text. For instance, you can send an image back, a PDF file or a Flash file or something like that.

Again, you will first have to set the Content-Type header to the type matching the data you are sending back. For instance, the content type for a PNG image is image/png.

You can search for “mime types” in your favourite search engine to find a list of mime types (content types), so you can find the mime type for the content you are sending back.

In order to write binary data back to the browser you cannot use the Writer obtained from response.getWriter(). Afterall, Writer’s are intended for text.

Instead you have to use the OutputStream obtained from the response.getOutputStream() method. Here is how:

OutputStream outputStream = response.getOutputStream();
outputStream.write(...);

Redirecting to a Different URL

You can redirect the browser to a different URL from your servlet. You cannot send any data back to the browser when redirecting. Here is how you redirect:

response.sendRedirect("https://www.dineshonjava.com");

Create the HTTP response

After the servlet request code, add the response code:

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ServletSample extends HttpServlet
{

   public void doGet (HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
   {

      Enumeration keys;
      String key;
      String myName = "";
      keys = request.getParameterNames();
      while (keys.hasMoreElements())
      {
         key = (String) keys.nextElement();
         if (key.equalsIgnoreCase("myName")) myName = request.getParameter(key);
      }
      System.out.println("Name = ");
      if (myName == "") myName = "Hello";

      response.setContentType("text/html"); 
      response.setHeader("Pragma", "No-cache");
      response.setDateHeader("Expires", 0);
      response.setHeader("Cache-Control", "no-cache");
   
      PrintWriter out = response.getWriter(); 
      out.println("<html>");  
      out.println("<head><title>Just a basic servlet</title></head>");
      out.println("<body>");
      out.println("<h1>Just a basic servlet</h1>");
      out.println ("<p>" + myName +  ", this is a very basic servlet.");
      out.println("</body></html>");    
      out.flush();

   }
}

 

<<Previous <<   || Index ||   >>Next >>

 

 

Previous
Next