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 a document. A typical response is shown below:
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 (HTTP/1.1 in this case), a status code (200 in this case), and a short message corresponding to the status code (OK in this case).
The following table summarizes the most useful HTTP 1.1 response headers returned from the web server to the browser. You will use them frequently 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 are:public、privateorno-cacheetc. Public means the document is cacheable, Private means the document is a single user's private document and can only be stored in a private (non-shared) cache, and no-cache means the document should not be cached. |
| Connection | This header indicates whether the browser uses a persistent HTTP connection. The valuecloseindicates that the browser does not use a persistent HTTP connection, and the valuekeep-alivemeans using a persistent connection. |
| Content-Disposition | This header allows you to ask the browser to prompt the user to save the response to disk as a file with the given name. |
| Content-Encoding | During transmission, this header specifies the encoding of the page. |
| Content-Language | This header indicates the language in which the document was 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 when the content expires, after which the content is no longer cached. |
| Last-Modified | This header indicates the last modified time of the document. The client can then cache the file and, in subsequent requests, provide a date through theIf-Modified-Sincerequest header. |
| Location | This header should be included in all responses with a status code. Within the 300s range, this tells the browser the address of the document. 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 for the page to refresh. |
| Retry-After | This header can be used with the 503 (Service Unavailable) response to tell the client how long it should wait before repeating its request. |
| Set-Cookie | This header 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 available through theHttpServletResponseobject.
| No. | Method & Description |
|---|---|
| 1 | String encodeRedirectURL(String url) Encodes the specified URL used in the sendRedirect method, or returns the URL unchanged if encoding is not necessary. |
| 2 | String encodeURL(String url) Encodes the specified URL that contains the session ID, or returns the URL unchanged if encoding is not necessary. |
| 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 whether 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 present in the buffer, including the status code and headers. |
| 11 | void resetBuffer() Clears the content of the underlying buffer in the response without clearing the status code and headers. |
| 12 | void sendError(int sc) Sends an error response to the client using the specified status code and clears 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 response body. |
| 16 | void setCharacterEncoding(String charset) Sets the character encoding (MIME charset) of the response sent to the client, e.g., UTF-8. |
| 17 | void setContentLength(int len) Sets the length of the content body in the HTTP Servlet response. This method sets the HTTP Content-Length header. |
| 18 | void setContentType(String type) If the response has not been committed, sets the content type of the response sent to the client. |
| 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) If the response has not been committed, sets the locale of the response. |
| 23 | void setStatus(int sc) Sets the status code for this response. |
HTTP Header Response Example
You have already seen the setContentType() method in the previous examples. The following example also uses the same method. In addition, we will use thesetIntHeader()method to set theRefreshheader.
//导入必需的 java 库
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")
//扩展 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;charset=UTF-8");
//使用默认时区和语言环境获得一个日历
Calendar cale = Calendar.getInstance();
//将Calendar类型转换成Date类型
Date tasktime=cale.getTime();
//设置日期输出的格式
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//格式化输出
String nowTime = df.format(tasktime);
PrintWriter out = response.getWriter();
String title = "自动刷新 Header 设置 - 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>当前时间是:" + nowTime + "</p>\n");
}
// 处理 POST 方法请求的方法
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:
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<!-- 类名 -->
<servlet-name>Refresh</servlet-name>
<!-- 所在的包 -->
<servlet-class>com.example.test.Refresh</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Refresh</servlet-name>
<!-- 访问的网址 -->
<url-pattern>/TomcatTest/Refresh</url-pattern>
</servlet-mapping>
</web-app>
Now, calling the above Servlet will display the current system time every 5 seconds. Simply run the Servlet and wait a moment, and you will see the following result:
