Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Servlet Server HTTP Response

Servlet Server HTTP Response

As discussed in the previous chapter, when a Web server responds to an HTTP request, the response typically consists of 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)





...



...





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

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 supported by the server (GET, POST, etc.).
Cache-Control This header specifies under what conditions the response document can be safely cached. The 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.
Connection This header indicates whether the browser uses a persistent HTTP connection. The value close indicates that the browser does not use a persistent HTTP connection, and the value keep-alive means a persistent connection is used.
Content-Disposition This header allows you to ask the browser to have the user save the response to disk as a file with a 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 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 expires and 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 later requests, via the If-Modified-Since request header provide a date.
Location This header should be included in all responses with a status code. Within 300s, this informs the browser of the document's address. The browser will automatically reconnect to this location and fetch 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 refreshes.
Retry-After This header can be used in conjunction with a 503 (Service Unavailable) response, which tells 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 provided by the HttpServletResponse object.

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 required.
2 String encodeURL(String url)
Encodes the specified URL to include the session ID, or returns the URL unchanged if encoding is not required.
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 already 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 contents 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, for example, 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 yet 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 yet 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 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 the Refresh header with the new document URL.



//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 for handling GET requests

      public void doGet(HttpServletRequest request,

                        HttpServletResponse response)

                throws ServletException, IOException

      {

          // Set auto-refresh load time to 5 seconds

          response.setIntHeader("Refresh", 5);

          // Set response content type

          response.setContentType("text/html;charset=UTF-8");

         

          //Get a calendar using the default timezone and locale

          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");  

          //Format output

          String nowTime = df.format(tasktime);

          PrintWriter out = response.getWriter();

          String title = "Auto-Refresh Header Settings - Runoob Tutorial Example";

          String docType =

          "\n";

          out.println(docType +

            "\n" +

            "" + title + "\n"+

            "\n" +

            "

" + title + "

\n" +      "

当前时间是:" + nowTime + "

\n");      }      // Method to handle POST requests      public void doPost(HttpServletRequest request,      HttpServletResponse response)      throws ServletException, IOException {      doGet(request, response);      } }

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



  

  

    

       

    Refresh  

      

    com.runoob.test.Refresh  

    

    

    Refresh  

      

    /TomcatTest/Refresh  

      

 

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