Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Servlet server HTTP response


May 14, 2021 Servlet


Table of contents


Servlet server HTTP response

As discussed in the previous section, when a Web server responds to an HTTP request, the response typically includes a status line, some response headers, an empty line, and a 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>

The status lines include 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 that you return to your browser from the web server side, which you use frequently in web programming:

Head information describe
Allow This header information specifies the request method (GET, POST, etc.) supported by the server.
Cache-Control This header information specifies that the response document can be securely cached safely.Possible values are: public、private or no-cache Wait.Public means that the document is cache. Private means that the document is a single user private document, and can only be stored in a private (non-shared) cache, NO-Cache means that the document should not be cached.
Connection This header information indicates whether the browser uses a persistent HTTP connection.value close Indicates that the browser does not use a lasting HTTP connection, value keep-alive It means using a persistent connection.
Content-Disposition This header information allows you to request a browser to save the response to a disk in a file for a given name.
Content-Encoding In the transmission process, this header information specifies the encoding method of the page.
Content-Language This header information indicates the language used by the document.For example, En, EN-US, RU, etc.
Content-Length This header information indicates the number of bytes in the response.This information is only required when the browser uses a long-lasting (Keep-Alive) HTTP connection.
Content-Type This header information provides a MIME (MultiPurpose Internet mail extension) type of the document.
Expires This header information specifies the time expired, after which content is no longer cached.
Last-Modified This header information indicates the final modification time of the document.Then, the client can cache files and pass through future requests. If-Modified-Since Request header information provides a date.
Location This header information should be included in all of the status codes.In 300s, this will notify the browser documentation.The browser will automatically reconnect to this location and get a new document.
Refresh This header information specifies how the browser should request an updated page as soon as possible.You can specify the number of seconds of the page refreshed.
Retry-After This header information can be used in conjunction with 503 (Service Unavailable Service Unavailable), which will tell the client to repeat it.
Set-Cookie This header specifies a cookie associated with the page.

How to set up http response headers

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

Serial number Method & Description
1 String encodeRedirectURL(String url)
Code is performed for the specified URL used in the SendRedirect method, or if the encoding is not required, the URL has not changed.
2 String encodeURL(String url)
The specified URL containing the session session ID is encoded or if the encoding is not required, the URL has not changed.
3 boolean containsHeader(String name)
Returns a boolean value indicating whether a named response header has been set.
4 boolean isCommitted()
Returns a Boolean value indicating whether the response has been submitted.
5 void addCookie(Cookie cookie)
Add the specified cookie to the response.
6 void addDateHeader(String name, long date)
Add a response header with a given name and date value.
7 void addHeader(String name, String value)
Add a response header with a given name and value.
8 void addIntHeader(String name, int value)
Add a response header with a given name and integer value.
9 void flushBuffer()
Forcing any content in the buffer is written to the client.
10 void reset()
Clear any data existing in the buffer, including the status code and head.
11 void resetBuffer()
Clear the contents of the underlying buffer in the response, not clear the status code and head.
12 void sendError(int sc)
Send an error response to the client using the specified status code and clear the buffer.
13 void sendError(int sc, String msg)
Send an error response to the client using the specified state.
14 void sendRedirect(String location)
Send a temporary redirect response to the client using the specified redirected position URL.
15 void setBufferSize(int size)
In response to the preferred buffer size.
16 void setCharacterEncoding(String charset)
A character encoding (MIME character set) that is sent to the client's response (MIME character set), for example, UTF-8.
17 void setContentLength(int len)
Set the length of the content body in the HTTP Servlet response, the method sets the HTTP Content-Length header.
18 void setContentType(String type)
If the response is not submitted, the content type of the response sent to the client is sent.
19 void setDateHeader(String name, long date)
Set a response header with a given name and date value.
20 void setHeader(String name, String value)
Set a response header with a given name and value.
21 void setIntHeader(String name, int value)
Set a response header with a given name and integer value.
22 void setLocale(Locale loc)
If the response is not submitted, the area where the response is set.
23 void setStatus(int sc)
Set the status code for the response.

HTTP Header responds to instances

You've seen the setContentType() method in the previous instance, and the following example uses the same method, and we'll set the Refresh header with the setIntHeader() method.

// 导入必需的 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 servlet above and the current system time is displayed every 5 seconds. Just run the servlet and wait a few moments to see the following results:

The Header settings are automatically refreshed

The current time is: 9:44:50 PM