English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Servlet Server 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 is as follows:

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

Status line includes the HTTP version (in this example, HTTP/1.1), a status code (in this example, 2(00) and a corresponding short message (in this example, OK).

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

HeaderDescription
AllowThis header information specifies the request methods supported by the server (GET, POST, etc.).
Cache-ControlThis header information specifies under what circumstances the response document can be safely cached. Possible values include:public, private or no-cache etc. Public means that the document is cacheable, Private means that the document is a private document for a single user and can only be stored in private (non-shared) cache, no-cache means that the document should not be cached.
ConnectionThis header information indicates whether the browser uses a persistent HTTP connection. Value close indicates that the browser does not use a persistent HTTP connection, value keep-alive means using a persistent connection.
Content-DispositionThis header information allows you to request the browser to save the response to the disk with the given file name.
Content-EncodingDuring the transmission process, this header information specifies the encoding method of the page.
Content-LanguageThis header information indicates the language used to write the document. For example, en, en-us, ru, etc.
Content-LengthThis header information indicates the number of bytes in the response. It is only used when the browser uses a persistent (keep)-These pieces of information are needed only when there is a persistent (keep alive) HTTP connection.
Content-TypeThis header information provides the MIME (Multipurpose Internet Mail Extension) type of the response document.
ExpiresThis header information specifies the time when the content expires, after which the content will no longer be cached.
Last-ModifiedThis header information indicates the last modification time of the document. Then, the client can cache the file and use it in subsequent requests through If-Modified-Since The request header information provides a date.
LocationThis header information should be included in all responses with status codes. In 3Within 00s, this will notify the browser of the document address. The browser will automatically reconnect to this location and retrieve the new document.
RefreshThis header information specifies how the browser should request the updated page as soon as possible. You can specify the number of seconds for page refresh.
Retry-AfterThis header information can be used with 503Used in conjunction with the (Service Unavailable service unavailable) response to tell the client how long it can repeat its request.
Set-CookieThis header information specifies a cookie associated with the page.

Methods for setting HTTP response headers

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

Serial NumberMethod & Description
1String encodeRedirectURL(String url)
Encode the specified URL for use with the sendRedirect method, or return the URL unchanged if encoding is not necessary.
2String encodeURL(String url)
Encode the specified URL containing the session ID, or return the URL unchanged if encoding is not necessary.
3boolean containsHeader(String name)
Return a boolean value indicating whether a named response header has already been set.
4boolean isCommitted()
Return a boolean value indicating whether the response has already been committed.
5void addCookie(Cookie cookie)
Add the specified cookie to the response.
6void addDateHeader(String name, long date)
Add a response header with a given name and date value.
7void addHeader(String name, String value)
Add a response header with a given name and value.
8void addIntHeader(String name, int value)
Add a response header with a given name and integer value.
9void flushBuffer()
Force any content in the buffer to be written to the client.
10void reset()
Clear any existing data in the buffer, including the status code and headers.
11void resetBuffer()
Clear the content of the basic buffer in the response, but do not clear the status code and headers.
12void sendError(int sc)
Send an error response to the client with the specified status code, and clear the buffer.
13void sendError(int sc, String msg)
Send an error response to the client with the specified status.
14void sendRedirect(String location)
Send a temporary redirect response to the client using the specified redirect location URL.
15void setBufferSize(int size)
Set the preferred buffer size for the response body.
16void setCharacterEncoding(String charset)
Set the character encoding (MIME character set) of the response sent to the client, for example, UTF-8.
17void setContentLength(int len)
Set the length of the content body in the HTTP Servlet response, this method sets the HTTP Content-Length header.
18void setContentType(String type)
If the response has not been submitted yet, set the content type of the response sent to the client.
19void setDateHeader(String name, long date)
Set a response header with a given name and date value.
20void setHeader(String name, String value)
Set a response header with a given name and value.
21void setIntHeader(String name, int value)
Set a response header with a given name and integer value.
22void setLocale(Locale loc)
If the response has not been submitted yet, set the response locale.
23void setStatus(int sc)
Set the status code for the response.

HTTP Header Response Example

You have seen the setContentType() method in the previous example, the following example also uses the same method, in addition, we will use setIntHeader() Method to set Refresh Header.

//Import the 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 the HttpServlet class
public class Refresh extends HttpServlet {
    // Method to handle GET method requests
      public void doGet(HttpServletRequest request,
                        HttpServletResponse response)
                throws ServletException, IOException
      {
          // Set the automatic reload time 5 seconds
          response.setIntHeader("Refresh", 5);
          // Set the response content type
          response.setContentType("text/html;charset=UTF-8");
         
          //Get a calendar with the default time zone and language environment  
          Calendar cale = Calendar.getInstance();  
          //Convert Calendar type to Date type  
          Date tasktime=cale.getTime();  
          //Set the date output format  
          SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
          //Formatted Output  
          String nowTime = df.format(tasktime);
          PrintWriter out = response.getWriter();
          String title = "Automatic Refresh Header Setting" - Basic Tutorial Website Example";
          String docType =
          "<!DOCTYPE html>\n";
          out.println(docType +
            "<html>\n" +
            "<head><title>" + title + "</title></head>\n"+
            "<body bgcolor="#f0f0f0">\n" +
            "<h1 align="center">" + title + "</h1>\n" +
            "<p>The current time is:" + nowTime + "</p>\n");
      }
      // method to handle POST method requests
      public void doPost(HttpServletRequest request,
                         HttpServletResponse response)
          throws ServletException, IOException {
         doGet(request, response);
      }
}

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

<?xml version="1.0" encoding="UTF-8"?>  
<web-app>  
  <servlet  
     <!-- class name -->  
    <servlet-name>Refresh</servlet-name>  
    <!-- the package -->  
    <servlet-class>com.w3codebox.test.Refresh</servlet-class>  
  </servlet>  
  <servlet-mapping>  
    <servlet-name>Refresh</servlet-name>  
    <!-- visited URL -->  
    <url-pattern>/TomcatTest/Refresh</url-pattern>  
    </servlet-mapping>  
</web-app>

Now, call the above Servlet every 5 The seconds will display the current system time. Just run the Servlet and wait a moment, and you will see the following result: