Servlet server HTTP response


As discussed in 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 documentation. 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 string corresponding to the status code. message (OK in this case).

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

Header informationDescription
AllowThis header information specifies the request method supported by the server ( GET, POST, etc.).
Cache-ControlThis header specifies the circumstances under which the response document can be safely cached. Possible values ​​are: public, private or no-cache etc. Public means the document is cacheable, Private means the document is private to a single user and can only be stored in a private (non-shared) cache, and no-cache means the document should not be cached.
ConnectionThis header indicates whether the browser uses persistent HTTP connections. The value close instructs the browser not to use persistent HTTP connections, and the value keep-alive means to use persistent connections.
Content-DispositionThis header allows you to request the browser to ask the user to save the response to disk in a file with a given name.
Content-Encoding During the transmission process, this header information specifies the encoding method of the page.
Content-LanguageThis header information indicates the language used in document writing. For example, en, en-us, ru, etc.
Content-LengthThis header indicates the number of bytes in the response. This information is only required if the browser uses 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. The client can then cache the file and provide a date in future requests via the If-Modified-Since request header.
LocationThis header should be included in all responses with a status code. Within 300s, this notifies the browser of the document's address. The browser will automatically reconnect to this location and fetch the new document.
RefreshThis header specifies how quickly the browser should request updated pages. You can specify the number of seconds after which the page refreshes.
Retry-AfterThis header can be used in conjunction with a 503 (Service Unavailable) response, which tells the client how long it takes to repeat its request. .
Set-CookieThis 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 Servlet programs. These methods are available through the HttpServletResponse object.

Serial numberMethod & Description
1String encodeRedirectURL(String url)
Encode the specified URL used in the sendRedirect method, or if encoding is not required, return the URL unchanged.
2String encodeURL(String url)
Encode the specified URL containing the session ID, or if encoding is not required , the returned URL remains unchanged.
3boolean containsHeader(String name)
Returns a Boolean value indicating whether the named response header has been set.
4boolean isCommitted()
Returns a Boolean value indicating whether the response has been committed.
5void addCookie(Cookie cookie)
Add the specified cookie to the response.
6void addDateHeader(String name, long date)
Adds a response with the given name and date value masthead.
7void addHeader(String name, String value)
Add a response header with the given name and value .
8void addIntHeader(String name, int value)
Adds a response with the given name and integer value masthead.
9void flushBuffer()
Forces any content in the buffer to be written to the client.
10void reset()
Clears any data present in the buffer, including status codes and headers.
11void resetBuffer()
Clears the contents of the underlying buffer in the response without clearing the status code and headers.
12void sendError(int sc)
Sends an error response to the client using the specified status code and clears the buffer .
13void sendError(int sc, String msg)
Sends an error response to the client using the specified status.
14void sendRedirect(String location)
Sends 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)
Sets the content of the response sent to the client if the response has not been submitted yet type.
19void setDateHeader(String name, long date)
Sets a response header with the given name and date value.
20void setHeader(String name, String value)
Set a response header with the given name and value .
21void setIntHeader(String name, int value)
Sets a response with the given name and integer value masthead.
22void setLocale(Locale loc)
If the response has not been submitted yet, set the response area.
23void setStatus(int sc)
Set the status code for this response.

HTTP Header Response Example

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

// 导入必需的 java 库
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
 
// 扩展 HttpServlet 类
public class Refresh extends HttpServlet {
 
  // 处理 GET 方法请求的方法
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
  {
      // 设置刷新自动加载时间为 5 秒
      response.setIntHeader("Refresh", 5);
 
      // 设置响应内容类型
      response.setContentType("text/html");
 
      // Get current time
      Calendar calendar = new GregorianCalendar();
      String am_pm;
      int hour = calendar.get(Calendar.HOUR);
      int minute = calendar.get(Calendar.MINUTE);
      int second = calendar.get(Calendar.SECOND);
      if(calendar.get(Calendar.AM_PM) == 0)
        am_pm = "AM";
      else
        am_pm = "PM";
 
      String CT = hour+":"+ minute +":"+ second +" "+ am_pm;
    
      PrintWriter out = response.getWriter();
      String title = "自动刷新 Header 设置";
      String docType =
      "<!doctype html public \"-//w3c//dtd html 4.0 " +
      "transitional//en\">\n";
      out.println(docType +
        "<html>\n" +
        "<head><title>" + title + "</title></head>\n"+
        "<body bgcolor=\"#f0f0f0\">\n" +
        "<h1 align=\"center\">" + title + "</h1>\n" +
        "<p>当前时间是:" + CT + "</p>\n");
  }
  // 处理 POST 方法请求的方法
  public void doPost(HttpServletRequest request,
                     HttpServletResponse response)
      throws ServletException, IOException {
     doGet(request, response);
  }
}

Now, call the above Servlet and the current system time will be displayed every 5 seconds. Just run the Servlet and wait for a while, you can see the following results:

Automatically refresh Header settings

The current time is: 9: 44:50 PM