YouTip LogoYouTip

Servlet Server 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 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 (in this case, HTTP/1.1), a status code (in this case, 200), and a short message corresponding to the status code (in this case, OK). 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 circumstances the response document can be safely cached. Possible values include **public**, **private**, or **no-cache**, etc. Public means the document is cacheable, Private means the document is for a single user's private use 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 should use a persistent HTTP connection. The value **close** indicates the browser should not use a persistent HTTP connection, while the value **keep-alive** means a persistent connection should be used. | | Content-Disposition | This header allows you to request the browser to save the response to disk with a given filename. | | Content-Encoding | This header specifies the encoding method of the page during transmission. | | Content-Language | This header indicates the language used to write the document. 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 should no longer be cached. | | Last-Modified | This header 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. | | Location | This header should be included in all responses with a status code. In the 300s range, 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 for the page refresh. | | Retry-After | This header can be used with a 503 (Service Unavailable) response to tell the client how long to wait before repeating its request. | | Set-Cookie | This header specifies a cookie associated with the page. | The following methods can be used to set HTTP response headers in a Servlet program. These methods are available through the _HttpServletResponse_ object. | No. | Method & Description | | --- | --- | | 1 | **String encodeRedirectURL(String url)** Encodes the specified URL for use in the sendRedirect method, or returns the URL unchanged if encoding is not necessary. | | 2 | **String encodeURL(String url)** Encodes the specified URL containing a 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 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 that exists 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 being 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)** Sets the content type of the response being sent to the client, if the response has not been committed. | | 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)** Sets the locale of the response, if the response has not been committed. | | 23 | **void setStatus(int sc)** Sets the status code for this response. | You have already seen the setContentType() method in previous examples. The following example also uses the same method, and additionally, we will use the **setIntHeader()** method to set the **Refresh** header. ```java //Import required 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 to handle GET method request. public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set refresh, autoload time as 5 seconds response.setIntHeader("Refresh", 5); // Set response content type response.setContentType("text/html;charset=UTF-8"); //Use default time zone and locale to get a Calendar Calendar cale = Calendar.getInstance(); //Convert Calendar type to Date type Date tasktime=cale.getTime(); //Set the format for date output SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //Format and output String nowTime = df.format(tasktime); PrintWriter out = response.getWriter(); String title = "Automatic Page Refresh - Tutorial Example"; String docType = "n"; out.println(docType + "n" + "" + title + "n"+ "n" + "

" + title + "

n" + "

Current Time is: " + nowTime + "

n"); } // Method to handle POST method request. public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } The above test example is located under the TomcatTest project, with the corresponding web.xml configuration as follows: ```xml Refresh com.tutorial.test.Refresh Refresh /TomcatTest/Refresh Now, calling the above Servlet will display the current system time every 5 seconds. Just run the Servlet and wait a moment, and you will see the following result: !(#)
← Servlet Http Status CodesServlet Client Request β†’