8. Set an HTTP response

zhaozj2021-02-16  156

8.1 HTTP response header Overview The HTTP response of the web server is generally composed of the following: a status line, one or more responses, one blank, content document. Setting the HTTP response head tends to combine the status code in the setting status line. For example, several status code indicating "document location has changed" accompanied by a location head, and 401 (Unauthorized) status code must be accompanied by a WWW-Authenticate header. However, even when there is no special sense of state code, the specified response head is also useful. The response head can be used to complete: set cookies, specify the change date, indicating that the browser refreshes the new page according to the specified intervals, declares the length of the document to take advantage of lasting HTTP connection, ... and more many other tasks. Setting the most commonly used method of respondent is HTTPSERVLETRESPONSE's setHead, which has two parameters, indicating the name and value of the response head, respectively. Similar to setting status code, setting the response heads should be performed before sending any document content. The setDateHeader method and the setInTheadr method are specifically used to set the response to the date and integer value. The former avoids the trouble of converting Java time into a GMT time string, and the latter avoids the inclusion of integers into a string. HttpservletResponse also provides a number of simplicity methods for setting up common responses, as follows: setContentType: Sets the Content-Type header. Most servlets use this method. SetContentLength: Sets Content-Length Head. This function is useful for browsers that support persistent HTTP connections. AddCookie: Set a cookie (there is no setcookie method in the Servlet API, because response often contains multiple set-cookie headers). In addition, as described in the previous section, the SendRedirect method sets the local code 302 will also set the location header. 8.2 Common responses and its meaning about HTTP head detailed and complete descriptions, see http://www.w3.org/protocols/ specification. Respondent Description ALOW server supports which request methods (such as get, post, etc.). The encoding method of the Content-Encoding document. Only the content type specified by the Content-Type header can only be obtained after decoding. The use of GZIP compressed documents can significantly reduce the download time of the HTML document. Java's GzipOutPutStream can easily compress Gzip, but only IE 4 on the Netscape and Windows on UNIX, IE 5 supports it. Therefore, servlet should check if the browser supports Gzip by viewing an accept-encoding header ("Accept-encoding")), returning to the Gzip compressed HTML page for other browsers to return to the Gzip-compressed HTML page to support Gzip's browser. page. Content-length represents the length of the content. This data is only required when the browser uses a persistent HTTP connection. If you want to use the advantage of a lasting connection, you can write the output document to ByteArrayoutputstram. After the completion is complete, then put this value into the Content-Length header, and finally send content by ByteaRrayStream.Writto (response.getputstream (). Content. Content. Content. Content. Content -Type indicates what MIME type belongs to the following document.

The servlet defaults to Text / Plain, but it usually needs to be explicitly designated as Text / HTML. Since CONTENT-TYPE is often set, HTTPSERVLETRESPONSE provides a dedicated method setContentTyep. Date current GMT time. You can use SetDateHeader to set this head to avoid the trouble of conversion time format. When expires should think that the document has expired, no longer cache it? The last change time of the Last-Modified document. Customers can provide a date via the if-modified-since request header, which will be considered a condition GET, and only the change time is later than the document for the specified time, otherwise returns a 304 (Not Modified) state. Last-Modified can also be set with a SetDateHeader method. Location means where the customer should go to extract the document. Location is usually not directly set, but through HttpservletResponse's SendRedirect method, this method simultaneously sets the status code 302. Refresh means that the browser should refresh the document after the browser will refresh the document in seconds. In addition to refreshing the current document, you can let the browser read the specified page by SetHeader ("Refresh", "5; URL = http: // host / path"). Note that this feature is usually achieved by setting , automatic refresh or redirection Those HTML writers that cannot use CGI or servlet are important. However, for servlet, it is more convenient to set the Refresh header. Note that refresh is "refreshing this page after n seconds or access the specified page" instead of "refreshing this page or accesses the specified page every N-second". Therefore, continuous refresh requirements send a Refresh header each time, while sending 204 status code, preventing browsers from continuing to refresh, whether using the refresh head or . Note that the Refresh head is not part of the HTTP 1.1 formal specification, but an extension, but Netscape and IE support it. Server server name. Servlet generally does not set this value, but is set by the web server yourself. Set-cookie settings and page associated cookies. Servlet should not use Response.setHeader ("SET-Cookie", ...), but should use the dedicated method provided by HTTPSERVLETRESPONSE. See the discussion on cookie settings below. WWW-AUTHENTICATE CEO should provide what type of authorization information in the Authorization header? This head is required in the response containing the 401 (Unauthorized) status line. For example, Response.setHeader ("WWW-Authenticate", "Basic Realm = \" Executives\ "). Note that servlet does not perform this process, but allows the Mechanism of the web server to control the access (for example, .htaccess) of the password protection page (for example,. 8.3 Example: Automatic refresh page below when the content change is used to calculate a large number.

Because the calculation is very large (for example, 500) may take a lot of time, the servlet will immediately return the result that has been found and continues to calculate in the background. The background is calculated using a lower priority thread to avoid excessive performance of the Web server. If the calculation has not been completed, the servlet will continue to request new content after a few seconds by sending a refresh header. Note that in addition to the use of the HTTP response head, this example also shows the other two very valuable functions of the servlet. First, it indicates that the servlet can handle multiple concurrent connections, each has its own thread. Servlet maintains a VECTOR table for existing prime calculations, and matchs all of these requests by looking at the number of number of numbers (lengths of the pop-up list) and the number of numbers (lengths of each prime) Synchronize to this list. Second, this example is proved that the status information between the request in the servlet is very easy. Maintaining status information is a very troublesome thing in traditional CGI programming. Since the status information is maintained, the browser can access the ongoing calculation process when refreshing the page, and also allows the servlet to save a list of recent request results, when a new request specifies the same parameters as the recently requested parameters Return the result immediately. Primenumbers.java Note that the servlet is used to servletUtilities.java given earlier. Also use: Primelist.java, used to create a VECTOR of a prime number in the background thread; Primes.java, used to randomly generate large numbers of the Biginteger type, check whether they are prone. (This is slightly removed from Primelist.java and Primes. Java.

) 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 number"; out.println (servletutilities.headwithtitle (title) \ N " "

" title "

\ N " "

Primes Found with " Numdigits " or more Digits: " NumcurrentPrimes ". "; IF (islastResult) Out.println (" done search. "); Else Out.println (" Still Looking For " NumprimesRemaining " More ... "); Out.Println ("
    ") For (int i = 0; i " currentprimes.elementat (i));} out.println (""); out.println " ");} public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet (request, response);} // check if there are different types of requests (completed or are Calculate). // If there is, return an existing result instead of the new background thread.

转载请注明原文地址:https://www.9cbs.com/read-8983.html

New Post(0)