8. Set the HTTP Response Header

Source: Internet
Author: User

8.1 HTTP Response Header Overview

The HTTP Response of a Web server generally consists of one status line, one or more response headers, one blank line, and content document. Setting the HTTP response header is often combined with the status code in the Set status line. For example, several status codes indicating "the document Location has changed" are accompanied by a Location header, while the 401 (Unauthorized) status code must be accompanied by a WWW-Authenticate header.

However, it is useful to specify the Response Header even if the status code with special meanings is not set. The response header can be used to complete: Set the Cookie, specify the modification date, instruct the browser to refresh the page at the specified interval, and declare the document length so that persistent HTTP connections can be used ,...... And many other tasks.

The most common method to set the response header is the setHeader of HttpServletResponse. This method has two parameters, indicating the name and value of the Response Header, respectively. Similar to the set status code, the set response header should be performed before any document content is sent.

The setDateHeader and setIntHeadr methods are used to set the response headers containing dates and integers. The former avoids the trouble of converting Java time into GMT time strings, the latter avoids the trouble of converting integers into strings.

HttpServletResponse also provides many easy methods to set common response headers, as shown below:

SetContentType: Set the Content-Type header. Most servlets use this method.
SetContentLength: Set the Content-Length header. This function is useful for browsers that support persistent HTTP connections.
AddCookie: Set a Cookie (the Servlet API does not have the setCookie method, because the response usually contains multiple Set-Cookie headers ).
In addition, the Location header is also set when the sendRedirect method sets status code 302.
8.2 common response headers and their meanings

For more information about HTTP headers, see http://www.w3.org/protocols.

Response Header description
Which request methods (such as GET and POST) are supported by the Allow server ).
The Encoding (Encode) method of the Content-Encoding document. The Content Type specified by the Content-Type header can be obtained only after decoding. Gzip compression can significantly reduce the download time of HTML documents. Java GZIPOutputStream can be easily compressed by gzip, but it is supported only by Netscape on Unix and IE 4 and IE 5 on Windows. Therefore, Servlet should view the Accept-Encoding header (request. getHeader ("Accept-Encoding") checks whether the browser supports gzip, returns the gzip-compressed HTML page for a browser that supports gzip, and returns a common page for other browsers.
Content-Length indicates the Content Length. This data is required only when the browser uses a persistent HTTP connection. If you want to take advantage of persistent connections, you can write the output document to ByteArrayOutputStram, view its size, put the value in the Content-Length header, and finally use byteArrayStream. writeTo (response. content sent by getOutputStream.
Content-Type indicates the MIME Type of the subsequent document. Servlet is text/plain by default, but it must be explicitly specified as text/html. Because Content-Type is often set, HttpServletResponse provides a dedicated method setContentTyep.
The current GMT time of Date. You can use setDateHeader to set this header to avoid the trouble of converting the time format.
When should Expires consider that the document has expired and thus it is no longer cached?
The Last modification time of the Last-Modified document. You can use the If-Modified-Since request header to provide a date. This request is considered as a condition GET. Only documents whose modification time is later than the specified time will be returned, otherwise, a 304 (Not Modified) status is returned. Last-Modified can also be set using the setDateHeader method.
Location indicates where the customer should extract the document. Location is usually not set directly, but through the sendRedirect method of HttpServletResponse. This method also sets the status code to 302.
Refresh indicates the time after which the browser should Refresh the document, in seconds. In addition to refreshing the current document, you can also use setHeader ("Refresh", "5; URL = http: // host/path") to allow the browser to read the specified page.
Note that this feature is typically implemented by setting <META HTTP-EQUIV = "Refresh" CONTENT = "5; URL = http: // host/path"> In the HEAD area of the HTML page, because, automatic refresh or redirection is important for HTML writers who cannot use CGI or Servlet. However, for Servlet, it is more convenient to directly set the Refresh header.

Note that Refresh indicates "Refresh the page after N seconds or access the specified page", rather than "Refresh the page or access the specified page every N seconds ". Therefore, continuous refreshing requires that a Refresh header be sent each time, and sending the 204 status code can prevent the browser from refreshing, whether it's using the Refresh header or <META HTTP-EQUIV = "Refresh"...>.

Note that the Refresh header is not part of the official HTTP 1.1 Specification but an extension, but is supported by both Netscape and IE.

Server name. Servlet generally does not set this value, but is set by the Web server.
Set-Cookie: Set the Cookie associated with the page. Servlet should not use response. setHeader ("Set-Cookie",...), but should use the dedicated method addCookie provided by HttpServletResponse. For more information about Cookie settings, see the following section.
What type of Authorization information should the WWW-Authenticate client provide in the Authorization header? This header is required in the Response containing the 401 (Unauthorized) status row. For example, response. setHeader ("WWW-Authenticate", "BASIC realm = \" executives \"").
Note that Servlet generally does not handle this problem, but allows the Web server to control access to password-protected pages (for example,. htaccess ).



8.3 instance: the page is automatically refreshed when the content changes

The Servlet below is used to calculate the large prime number. Because it may take a lot of time to compute very large numbers (such as 500 bits), the Servlet will immediately return the results that have been found and continue computing in the background. Background computing uses a thread with a lower priority to avoid affecting the performance of Web servers too much. If the calculation is not complete, the Servlet sends a Refresh header to instruct the browser to continue requesting new content after a few seconds.

Note: This example not only describes the use of HTTP Response Headers, but also shows two other valuable functions of Servlet. First, it indicates that the Servlet can process multiple concurrent connections, each of which has its own thread. Servlet maintains a Vector table for the calculation request of an existing prime number. It queries the number of prime numbers (the length of the prime number list) and the number of numbers (the length of each prime number) match the current request with the existing request and synchronize all these requests to this list. Second, this example proves that it is very easy to maintain the status information between requests in the Servlet. Maintaining state information is troublesome in traditional CGI programming. Because the status information is maintained, the browser can access the ongoing computing process when refreshing the page, and also enables the Servlet to save a list of recent request results, if a new request has the same parameters as the latest request, the results can be returned immediately.

PrimeNumbers. java

Note that this Servlet uses the ServletUtilities. java given earlier. In addition, PrimeList. java is used to create a Vector of prime numbers in the background thread. Primes. java is used to randomly generate BigInteger-type big numbers and check whether they are prime numbers. (The Code of PrimeList. java and Primes. java is omitted here .)
Package hall;

Import java. io .*;
Import javax. servlet .*;
Import javax. servlet. http .*;
Import java. util .*;

Public class PrimeNumbers extends HttpServlet {
Private static Vector primeListVector = new Vector ();
Private static int maxPrimeLists = 30;

Public void doGet (HttpServletRequest request,
HttpServletResponse response)
Throws ServletException, IOException {
Int numPrimes = ServletUtilities. getIntParameter (request, "numPrimes", 50 );
Int numDigits = ServletUtilities. getIntParameter (request, "numDigits", 120 );
PrimeList primeList = findPrimeList (primeListVector, numPrimes, numDigits );
If (primeList = null ){
PrimeList = new PrimeList (numPrimes, numDigits, true );
Synchronized (primeListVector ){
If (primeListVector. size ()> = maxPrimeLists)
PrimeListVector. removeElementAt (0 );
PrimeListVector. addElement (primeList );
}
}
Vector currentPrimes = primeList. getPrimes ();
Int numCurrentPrimes = currentPrimes. size ();
Int numPrimesRemaining = (numPrimes-numCurrentPrimes );
Boolean isLastResult = (numPrimesRemaining = 0 );
If (! IsLastResult ){
Response. setHeader ("Refresh", "5 ");
}
Response. setContentType ("text/html ");
PrintWriter out = response. getWriter ();
String title = "Some" + numDigits + "-Digit Prime Numbers ";
Out. println (ServletUtilities. headWithTitle (title) +
"<Body bgcolor = \" # FDF5E6 \ "> \ n" +
"<H2 ALIGN = CENTER>" + title + "</H2> \ n" +
"<H3> Primes found with" + numDigits +
"Or more digits:" + numCurrentPrimes + ". </H3> ");
If (isLastResult)
Out. println ("<B> Done searching. </B> ");
Else
Out. println ("<B> Still looking for" + numPrimesRemaining +
"More <BLINK>... </BLINK> </B> ");
Out. println ("<OL> ");
For (int I = 0; I <numCurrentPrimes; I ++ ){
Out. println ("<LI>" + currentPrimes. elementAt (I ));
}
Out. println ("</OL> ");
Out. println ("</BODY> </HTML> ");
}

Public void doPost (HttpServletRequest request,
HttpServletResponse response)
Throws ServletException, IOException {
DoGet (request, response );
}

// Check whether a request of the same type exists (completed or computed ).
// If yes, the system returns the existing result instead of starting a new background thread.
Private PrimeList findPrimeList (Vector primeListVector,
Int numPrimes,
Int numDigits ){
Synchronized (primeListVector ){
For (int I = 0; I <primeListVector. size (); I ++ ){
PrimeList primes = (PrimeList) primeListVector. elementAt (I );
If (numPrimes = primes. numPrimes ())&&
(NumDigits = primes. numDigits ()))
Return (primes );
}
Return (null );
}
}
}




PrimeNumbers.html
<! Doctype html public "-// W3C // dtd html 4.0 Transitional // EN">
<HTML>
<HEAD>
<TITLE> Calculation of large prime numbers </TITLE>
</HEAD>
<CENTER>
<Body bgcolor = "# FDF5E6">
<Form action = "/servlet/hall. PrimeNumbers">
<B> calculate several prime numbers: </B>
<Input type = "TEXT" NAME = "numPrimes" VALUE = 25 SIZE = 4> <BR>
<B> Number of digits of each Prime Number: </B>
<Input type = "TEXT" NAME = "numDigits" VALUE = 150 SIZE = 3> <BR>
<Input type = "SUBMIT" VALUE = "Start Calculation">
</FORM>
</CENTER>
</BODY>
</HTML>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.