Easy Tutorial
❮ Servlet Environment Setup Servlet Http Status Codes ❯

Servlet HTTP Response

As discussed in the previous chapters, when a web server responds to an HTTP request, the response typically includes a status line, some response headers, a blank line, and the document. A typical response looks like this:

HTTP/1.1 200 OK
Content-Type: text/html
Header2: ...
...
HeaderN: ...
  (Blank Line)
<!doctype ...>
<html>
<head>...</head>
<body>
...
</body>
</html>

The status line includes the HTTP version (in this case, HTTP/1.1), a status code (in this case, 200), and a short message corresponding to the status code (in this case, OK).

The following table summarizes the most useful HTTP 1.1 response headers returned from the web server to the browser, which you will frequently use in web programming:

Header Description
Allow This header specifies the request methods (GET, POST, etc.) supported by the server.
Cache-Control This header specifies under what circumstances the response document can be safely cached. Possible values include: public, private, or no-cache. Public means the document is cacheable, Private means the document is for a single user and can only be stored in a private (non-shared) cache, no-cache means the document should not be cached.
Connection This header indicates whether the browser should use a persistent HTTP connection. The value close indicates the browser should not use a persistent HTTP connection, while keep-alive means a persistent connection should be used.
Content-Disposition This header allows you to request the browser to prompt the user to save the response to disk with a given name.
Content-Encoding This header specifies the encoding of the page during transmission.
Content-Language This header indicates the language in which the document is written. For example, en, en-us, ru, etc.
Content-Length This header indicates the number of bytes in the response. This information is only needed when the browser uses a persistent (keep-alive) HTTP connection.
Content-Type This header provides the MIME (Multipurpose Internet Mail Extension) type of the response document.
Expires This header specifies the time after which the content should no longer be cached.
Last-Modified This header indicates the last modification time of the document. The client can then cache the file and provide a date in future requests via the If-Modified-Since request header.
Location This header should be included in all responses with a status code. Within the 300s, this informs the browser of the document's address. The browser will automatically reconnect to this location and retrieve the new document.
Refresh This header specifies how soon the browser should request an updated page. You can specify the number of seconds after which the page should be refreshed.
Retry-After This header can be used with a 503 (Service Unavailable) response to tell the client when it can repeat its request.
Set-Cookie This header specifies a cookie associated with the page.

Methods to Set HTTP Response Headers

The following methods can be used to set HTTP response headers in a Servlet program. These methods are available through the HttpServletResponse object.

Number Method & Description
1 String encodeRedirectURL(String url) <br>Encodes the specified URL for use in the sendRedirect method, or returns the URL unchanged if no encoding is necessary.
2 String encodeURL(String url) <br>Encodes the specified URL by including the session ID in it, or returns the URL unchanged if no encoding is necessary.
3 boolean containsHeader(String name) <br>Returns a boolean indicating whether the named response header has already been set.
4 boolean isCommitted() <br>Returns a boolean indicating whether the response has been committed.
5 void addCookie(Cookie cookie) <br>Adds the specified cookie to the response.
6 void addDateHeader(String name, long date) <br>Adds a response header with the given name and date value.
// Import necessary Java libraries
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/Refresh")

// Extend HttpServlet class
public class Refresh extends HttpServlet {

    // Method to handle GET method request
    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
              throws ServletException, IOException
    {
        // Set auto-refresh time to 5 seconds
        response.setIntHeader("Refresh", 5);
        // Set response content type
response.setContentType("text/html;charset=UTF-8");

// Use the default time zone and locale to get a calendar
Calendar cale = Calendar.getInstance();
// Convert the Calendar type to Date type
Date tasktime = cale.getTime();
// Set the date output format
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// Format the output
String nowTime = df.format(tasktime);
PrintWriter out = response.getWriter();
String title = "Auto Refresh Header Setting - tutorialpro.org Example";
String docType =
"<!DOCTYPE html>\n";
out.println(docType +
  "<html>\n" +
  "<head><title>" + title + "</title></head>\n" +
  "&lt;body bgcolor=\"#f0f0f0\">\n" +
  "&lt;h1 align=\"center\">" + title + "</h1>\n" +
  "<p>Current time is: " + nowTime + "</p>\n");
}
// Method to handle POST method request
public void doPost(HttpServletRequest request,
                   HttpServletResponse response)
    throws ServletException, IOException {
   doGet(request, response);
}
}

The above test example is located under the TomcatTest project, with the corresponding web.xml configuration as follows:

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
  <servlet>
    <!-- Class name -->
    <servlet-name>Refresh</servlet-name>
    <!-- Package location -->
    <servlet-class>com.tutorialpro.test.Refresh</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Refresh</servlet-name>
    <!-- URL to access -->
    <url-pattern>/TomcatTest/Refresh</url-pattern>
  </servlet-mapping>
</web-app>

Now, when you call the above Servlet, it will display the current system time every 5 seconds. Simply run the Servlet and wait a moment to see the result as follows:

❮ Servlet Environment Setup Servlet Http Status Codes ❯