Difference and application of two redirection methods of servlet

xiaoxiao2021-03-06  81

One problem: In Servlet / JSP programming, there are two ways to achieve server output redirection, one is through the Forward method (such as in JSP, The other is a SendRedirect method that uses the Javax.Servlet.http.httpservletResponse interface (such as response.sendredirect ("OtherPage.JSP"); what is the difference and linking of these two methods? Let us look at the following analysis. Analysis: (1) This method is to use the server side to output the data to the buffer, before sending the contents of the buffer to the client, the original does not send, change to send the The contents of the page, if there is a lot of output before , the previous output has made the buffer, automatically output to the client, then this statement will not work, this should be paid special. Supplement knowledge: Output Buffer default: The server is output to the client's content, not directly written to the client, but write to an output buffer. Only the content of the buffer is only in the case of the following three Output to the client: 1 This JSP page has completed the output of the information 2 Output buffer is full of 3JSP to call out.Flush () or response.flushbuffer () output buffer size can be used: <% @ Page Buffer = "None" | "NKB"%> or response.setBuffersize () settings, as follows: 1 Set the size of the output buffer is 1KB. <% @ page buffer = "1kb"%> or response.setbuffearsize (1); 2 setting The size of the output buffer is 0, that is, it is not buffered. <% @ Page buffer = "none"%> or response.setbuffearsize (0); use response.getBuffersize () or out.getBuffersize () Output buffer size The unit is byte. Use response.iscommitted () to check if the server has output to the client. If the return value is True, the data has been output to the client, and it is not yet. (2) Response .Sendredirect ("OtherPage.JSP") This method changes the browser down to redirect instructions by modifying the HTTP protocol, so that the browser makes a request to request the URL specified in the location to make the browser display to redirect web pages. content. This method can accept absolute or relative URLs. If the parameter passed to the method is a relative URL, the web container converts it into an absolute URL before sending it to the client. If the address is relative, there is no '/', then the Web Container considers that it is relative to the current request URI.

Because this method is to modify the Header implementation of the HTTP protocol, the following method can also change the HTTP header attribute, the principle is the same. <% Response.setstatus (httpservletResponse.sc_moved_permanently); string newlocn = "/ Index.html "; Response.setHeader (" Location ", newlocn);%> Supplementary knowledge: HTTP response head web server responds to requests for browser or other client programs, their response is generally consisting of the following parts: a status line , Several responses, one blank, content documentation. Here is the simplest answer: http / 1.1 200 okcontent-type: text / plainhello world 1 Set the status information status row contains a short description of the HTTP version, status code, and status code. In most cases, all responses other than Content-Type are optional. Servlets can utilize status code to implement many functions. For example, you can redirect the user to another, just like the example we have seen on the side. Let's take this opportunity to specifically discuss the meaning of various status code and how to use these code. As mentioned earlier, the HTTP response status line contains HTTP versions, status code, and corresponding status information. Due to the status information is directly related to the status code, the HTTP version is determined by the server, so there is only one status code for servlet settings.

First give a common HTTP 1.1 status code and their corresponding status information and meanings, and specific usage methods we will make a detailed introduction. 100 Continue Initial request has been accepted, the customer should continue to send the rest of the request. (HTTP 1.1 new) 101 Switching Protocols server will follow the customer's request to another protocol (HTTP 1.1 new) 200 ok everything is normal, the answer document requesting the GET and POST requests back. If you don't have to set status code, the servlet uses the 202 status code by default. The 201 CREATED server has created a document, and the Location header gives its URL. 202 ACCEPTED has been accepted, but the processing has not been completed. 203 Non-Authoritative Information The document has returned normally, but some responses may not be correct because the document is used (HTTP 1.1 new). 204 no content does not have a new document, the browser should continue to display the original document. If the user regularly refreshes the page, the servlet can determine that the user document is new enough, and this status code is useful. 205 Reset Content has no new content, but the browser should reset the content it displayed. Used to force the browser to clear the form input content (HTTP 1.1 new). 206 Partial Content The customer sent a GET request with the Range header, which completed it (HTTP 1.1 new). 300 MULTIPLE Choices Customer Requests Documents can be found at multiple locations, which have been listed within the returned document. If the server wants to make a priority, you should indicate at the Location response. 301 MOVED Permanently Customer Request Document In other places, the new URL is given in the location header, and the browser should automatically access the new URL. 302 FOUND is similar to 301, but the new URL should be considered a temporary alternative, not permanent. Note that the corresponding status information in HTTP1.0 is "Moved Temporatily", and the corresponding constant in httpservletResponse is SC_MOVED_TEMPORARILY instead of sc_found. When this status code appears, the browser automatically accesses the new URL, so it is a very useful status code. To do this, servlet provides a dedicated method, namely SendRedirect. It is better to use Response.sendredirect (URL) than using response.setstatus (response.sc_moved_temporarily) and response.setheader ("Location", URL). This is because: First, the code is more concise. Second, use SendRedirect, servlet automatically construct a page containing new links (for old browsers that cannot be redirected). Finally, SendRedirect can handle relative URLs, automatically convert them into absolute URLs. Note that this status code is sometimes used for replacement with 301. For example, if the browser is incorrectly requests http: // Host / ~ User (missing behind the late slash), some servers return 301, and some returns 302.

Strictly speaking, we can only assume that the browser will automatically redirect when the original request is Get. See 307.

303 SEE Other is similar to 301/302, and the difference is that if the original request is POST, the redirect target document specified by the local header should be extracted (HTTP 1.1 new). 304 NOT MODIFIED The client has buffered documents and issues a conditional request (generally providing the IF-Modified-Since header indicating that the customer only updates the document updated than the specified date). The server tells customers that the original buffer document can also be used. 305 USE Proxy Customer Request documents should be extracted by the proxy server indicated by the Location header (HTTP 1.1 new). 307 Temporary Redirect and 302 (Found) are the same. Many browsers are incorrectly responding to the 302 response to redirect, even if the original request is POST, even if it actually only responds to the POST request is 303, it can be redirected. For this reason, HTTP 1.1 has increased by 307 to more clear the regional division of state code: When the 303 response occurs, the browser can follow the redirected GET and POST requests; if it is 307 response, the browser can only follow Redirection to the GET request. Note that there is no corresponding constant for the status code in HTTPSERVLETRESPONSE. (HTTP 1.1 new)

400 Bad Request requests a syntax error. 401 Unauthorized Customers attempt to access the password-protected page without authorization. A WWW-Authenticate header will contain a www-authenticate header, the browser displays the user's name / password dialog, and then issues a request after filling the appropriate Authorization header. 403 Forbidden resource is not available. The server understands the customer's request, but refuses to handle it. It is usually caused due to the permissions settings of the file or directory on the server. 404 NOT FOUND Unable to find resources for the specified location. This is also a common response, HTTPSERVLETRESPONSE provides the corresponding method: Senderror (Message). 405 Method Not ALLOWED Request Method (GET, POST, HEAD, DELETE, PUT, TRAC, etc.) do not apply to the specified resource. (HTTP 1.1 new) 406 Not Acceptable Specifies the resource specified, but its MIME type and customer are not compatible (new HTTP 1.1) specified in the ACCPET header. 407 Proxy Authentication Required Similar to 401, the customer must first authorize the proxy server. (HTTP 1.1 new) 408 Request Timeout In the waiting time of the server license, customers have not issued any requests. Customers can repeat the same request later. (HTTP 1.1 new) 409 Conflict is usually related to the PUT request. Since the request and the current state of the resource conflict, the request cannot be successful. (HTTP 1.1 new) 410 Gone requested documentation is no longer available, and the server does not know which address should be redirected. The difference between it and 404 is that the return 407 indicates that the document is permanently left the specified location, and 404 indicates that the document is not available for unknown reason. (HTTP 1.1 new) 411 Length Required server cannot handle the request unless the customer sends a Content-Length header. (HTTP 1.1 new) 412 Precondition Failed requests some prerequisites fails (HTTP 1.1 new). 413 Request Entity Too Large The size of the target document exceeds the size of the server is currently willing to handle. If the server considers yourself to process the request later, you should provide a Retry -After header (HTTP 1.1 new). 414 Request Uri Too Long Uri is too long (HTTP 1.1 new). 416 Requested Range Not Satisfiable server does not satisfy the Range header specified in the request. (HTTP 1.1 new) 500 INTERNAL Server Error server encountered unexpected situations and cannot complete customer requests. The 501 Not Implemented server does not support the functions required to implement the request. For example, the customer issued a PUT request that the server is not supported. 502 BAD GATEWAY Server As a gateway or agent, in order to complete the request to access the next server, the server returns an illegal response. 503 Service UNAVAILALALABLE server has failed to respond due to maintenance or load. For example, servlet may return 503 in the case where the database connection pool is full. A Retry -After header can be provided when the server returns 503. 504 GATEWAY TIMEOUT is used by a server as a proxy or gateway, indicating that you cannot get a response from the remote server in time.

(HTTP 1.1 new) 505 HTTP Version Not Supported Server does not support the HTTP version indicated in the request. (HTTP 1.1 new) As mentioned earlier, the HTTP response status line contains HTTP versions, status code, and corresponding status information. Due to the status information is directly related to the status code, the HTTP version is determined by the server, so there is only one status code for servlet settings. Take the example of our top. One of these sentences is to set the status code of the HTTP response head, is: response.setstatus (httpservletResponse.sc_moved_permanently); Servlet Setting status code typically uses the HTTPSERVLETRESPONSE's setStatus method. The parameter of the setStatus method is an integer (ie, status code), but in order to make the code have better readability, it can be used to avoid direct use of integers in HTTPSERVLETRESPONSE. These constants are named in accordance with the standard status information in HTTP 1.1, and all the names add the SC prefix (STATUS CODE abbreviation) and uppercase, while converting spaces into underscores. That is, the status information corresponding to the status code 301 is "MOVED Permanently", the corresponding constant name in HTTPSERVLETRESPONSE is SC_MOVED_PERMANENTLY. However, there are two exceptions: The constant corresponding to the status code 302 is named SC_MOVED_TEMPORARILY according to HTTP 1.0, not SC_FOUND, and 307 has no corresponding constant. Although setting status code is typically used is a response.setstauts (int) method, HTTPSERVLETRESPONSE provides a dedicated method for both common situations: SendError method generates a 404 response while generating a short HTML error message document; The SendRedirect method generates a 302 response while indicating the URL of the new document in the local header. This method is the principle of the response.sendredirect ("OtherPage.JSP") mentioned earlier. It is a 301 response that the difference between the upper status list is not repeated here for the difference between RESPONSE.SETSTATUS. 2 Set the HTTP response head to set the HTTP response head tend 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. These are mentioned in the status information description of the corresponding state code. 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. Take the example of our previous example, one is to set the HTTP response head, is: response.sethead ("location", newlocn); setting the most common way to set the response head is HttpservletResponse's setHeader, this method has two parameters , Indicate 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.

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 later .Servlet defaults to text / plain, but it usually needs to be explicitly designated as Text / HTML. Since the 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 you think that the document has expired, no longer cache the last change time of the last-modified document. Customer can pass if- The Modified-Since request header provides a date that will be considered a condition GET, which only returns a document that is later than the specified time, otherwise returns a 304 (not modified) state. Last-Modified is also available in the SetDateHeader method. Setting. Location means that where is the client to extract the document. Location is usually not directly set, but through the HTTPSERVLETRESPONSE's sendRedirect method, the method simultaneously sets the status code to 302. Refresh indicates how much time it should be refreshed after the browser, in seconds In addition to refreshing the current document, you can also let the browser read the specified page via SetHeader ("Refresh", "5; URL = http: // host / path"). Note that this feature is usually passed Automatically refresh or redirect HTML that cannot use CGI or Servlet The writer is very important. However, for the servlet, it is more convenient to directly 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,.

At this way, we should understand the principle of resetting the following code: Modify the HTTP protocol's header section, let the browser to ask the browser to make a request to request the URL specified in the location, so that the browser displays The content of the web page. <% response.setstatus (httpservletResponse.sc_moved_persponse.sc_moved_persponse.sc_moved_persponse.sc_Moved_PrManently) Set http response head status code string newlocn = "/ index.html"; response.setheader ("location", newlocn); set HTTP response head%>

Three summary: Through the analysis, we know the principles of the two server-side redirecting methods, is the mechanism to output data to the buffer using the server side, send the contents of the buffer to the customer. Before the end, by the process of stopping the call page, the steering response will be executed, so that the relocation function is implemented, any content in the output buffer of the original modulus is not yet displayed (refresh) in the browser will be clear, no longer display. The response.sendredirect ("OtherPage.JSP") is a Header section of the HTTP protocol, let the browser make a request to request the URL specified in Loc to redirect the browser to the browser. contents.

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

New Post(0)