VII. HTTP response status

Source: Internet
Author: User

7.1 status code Overview

When a Web server responds to a request from a browser or another client program, its response is generally composed of the following parts: a status line, several response headers, a blank line, and content documentation. The following is a simple response:
HTTP/1.1 200 OK
Content-Type: text/plain

Hello World




The status line contains the HTTP Version, status code, and brief descriptions corresponding to the status code. In most cases, all Response Headers except Content-Type are optional. However, Content-Type is required. It describes the MIME Type of the subsequent documents. Although most responses contain a document, some do not. For example, responses to HEAD requests will never come with the document. Many status codes are actually used to identify a failed request, and these responses do not contain documents (or only contain a brief Error Message description ).

Servlet can use status code to implement many functions. For example, you can redirect a user to another website, instruct the following documents to be images, PDF files, or HTML files, and tell the user that a password is required to access the document. In this section, we will discuss the meaning of various status codes and what they can do.

7.2 set status code

As mentioned above, the HTTP response status line contains the HTTP Version, status code, and corresponding status information. Because the status information is directly related to the status code, and the HTTP Version is determined by the server, only one status code needs to be set by the Servlet.

The Servlet configuration status code generally uses the setStatus method of HttpServletResponse. The parameter of the setStatus method is an integer (that is, the status code). To make the code more readable, you can use constants defined in HttpServletResponse to avoid using integers directly. These constants are named based on the standard Status information in HTTP 1.1. All names are prefixed with SC (short for Status Code) and capitalized, and spaces are converted into underscores. That is to say, if the status information corresponding to Status Code 404 is "Not Found", the corresponding constant name in HttpServletResponse is SC _NOT_FOUND. But there are two exceptions: the constant corresponding to status code 302 is named according to HTTP 1.0, and 307 does not have the corresponding constant.

Setting the status code does not always mean that documents are not returned. For example, although most servers output a simple "File Not Found" message when returning a 404 response, the Servlet can also customize this response. However, you should call response. setStatus before sending any content through PrintWriter.

Although the set Status Code generally uses response. setStauts (int) method, but for the sake of simplicity, HttpServletResponse provides a dedicated method for two common cases: the sendError method generates a 404 response and a short HTML error message document; the sendRedirect method generates a 302 response and specifies the URL of the new document in the Location header.

7.3 HTTP 1.1 Status Code and its meaning

The following table shows common HTTP 1.1 Status codes and their corresponding status information and meanings.

Exercise caution when using status code that only supports HTTP 1.1, because many browsers only Support HTTP 1.0. If you use the status code unique to HTTP 1.1, you 'd better check the HTTP Version of the request (by using the getProtocol method of HttpServletRequest ). Status Code status information meaning
100 the initial request for Continue has been accepted, and the customer shall Continue to send the rest of the request. (New HTTP 1.1)
101 Switching Protocols server converts a client-compliant request to another protocol (New in HTTP 1.1)
200 OK everything is normal, and the response document to the GET and POST requests follows. If you do not need setStatus to set the status code, the Servlet uses the 202 status code by default.
The 201 Created server has Created a document and the Location header provides its URL.
202 Accepted has Accepted the request, but the processing has not been completed.
203 the Non-Authoritative Information document has been returned normally, but some response headers may be incorrect because the document is copied (New in HTTP 1.1 ).
204 No Content does not have a new document. The browser should continue to display the original document. This status code is useful if the user regularly refreshes the page and the Servlet can determine that the user document is new enough.
205 there is no new Content in the Reset Content, but the browser should Reset the Content displayed by it. Used to force the browser to clear the input content of the form (New in HTTP 1.1 ).
206 Partial Content the client sent a GET request with a Range header, and the server completed it (HTTP 1.1 New ).
300 the documents requested by the Multiple Choices client can be found in Multiple locations, which are listed in the returned documents. If the server needs to give priority, it should be specified in the Location response header.
301 Moved Permanently the document requested by the customer is elsewhere. The new URL is provided 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 treated as a temporary alternative, rather than permanent. Note that the status information in HTTP1.0 is "Moved Temporatily", while the constant in HttpServletResponse is SC _MOVED_TEMPORARILY, rather than SC _FOUND.
When this status code appears, the browser can automatically access the new URL, so it is a very useful status code. To this end, Servlet provides a dedicated method, namely sendRedirect. Using response. sendRedirect (url) is better than using response. setStatus (response. SC _MOVED_TEMPORARILY) and response. setHeader ("Location", url. This is because:

First, the code is more concise.
Second, when sendRedirect is used, the Servlet will automatically construct a page containing new links (for older browsers that cannot be automatically redirected ).
Finally, sendRedirect can process relative URLs and automatically convert them into absolute URLs.
Note that this status code can be replaced with 301 sometimes. For example, if the browser mistakenly requests http: // host /~ If the user (with a slash missing), some servers return 301, and some return 302.

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

303 See Other is similar to 301/302. The difference is that if the original request is POST, the redirection target document specified by the Location header should be extracted through GET (New in HTTP 1.1 ).
304 The Not Modified client has a buffered document and issued a conditional request (generally, the If-Modified-Since header is provided to indicate that the customer only wants to update the document on a specified date ). The server tells the customer that the original buffer documentation can still be used.
305 the document requested by the Use Proxy client should be extracted by the Proxy server specified by the Location header (New in HTTP 1.1 ).
307 Temporary Redirect and 302 (Found) are the same. Many browsers mistakenly respond to the 302 response for redirection. Even if the original request is POST, it can only be redirected when the POST request actually responds to 303. For this reason, HTTP 1.1 adds 307 to clear the region code in several states: When a 303 response occurs, the browser can follow the redirected GET and POST requests; if a 307 response occurs, the browser can only follow the redirection to get requests.
Note that no constant is provided for the status code in HttpServletResponse. (New HTTP 1.1)

400 syntax error in Bad Request.
401 Unauthorized the customer attempted to access the password-protected page without authorization. The response contains a WWW-Authenticate header. the browser displays the username/password dialog box accordingly, and then sends a request again after entering the appropriate Authorization header.
403 Forbidden resources are unavailable. The server understands the customer's request, but rejects the request. This is usually caused by permission settings for files or directories on the server.
404 Not Found cannot find the resource at the specified position. This is also a common response. HttpServletResponse provides the corresponding method: sendError (message ).
405 Method Not Allowed request methods (GET, POST, HEAD, DELETE, PUT, TRACE, etc.) are Not applicable to specified resources. (New HTTP 1.1)
406 the resource specified by Not Acceptable has been found, but its MIME type is incompatible with the one specified by the customer in the Accpet header (New in HTTP 1.1 ).
407 Proxy Authentication Required is similar to 401, indicating that the customer must first be authorized by the Proxy server. (New HTTP 1.1)
408 Request Timeout the client has not sent any Request within the waiting time permitted by the server. The customer can repeat the same request later. (New HTTP 1.1)
409 Conflict is usually related to PUT requests. The request cannot be successful because the request conflicts with the current status of the resource. (New HTTP 1.1)
410 the document requested by Gone is no longer available, and the server does not know which address to redirect. It differs from 404 in that if 407 is returned, the document permanently leaves the specified position, and 404 indicates that the document is unavailable for unknown reasons. (New HTTP 1.1)
The 411 Length Required server cannot process the request unless the customer sends a Content-Length header. (New HTTP 1.1)
412 Precondition some of the prerequisites specified in the Failed Request Header fail (New in HTTP 1.1 ).
413 the size of the target Request Entity Too Large document exceeds the size that the server is willing to process. If the server thinks it can process the request later, it should provide a Retry-After header (New in HTTP 1.1 ).
414 Request URI Too Long URI is Too Long (HTTP 1.1 is new ).
416 the Requested Range Not Satisfiable server cannot meet the Range header specified by the customer in the request. (New HTTP 1.1)
500 the Internal Server Error Server encounters unexpected circumstances and cannot complete the customer's request.
501 The Not Implemented server does Not support the functions required to implement the request. For example, the customer sends a PUT request not supported by the server.
502 when the Bad Gateway server acts as a Gateway or proxy, the server returns an invalid response to access the next server to complete the request.
503 the Service Unavailable server fails to respond due to maintenance or overload. For example, Servlet may return 503 when the database connection pool is full. When the server returns 503, A Retry-After header can be provided.
504 Gateway Timeout is used by a proxy or Gateway server, indicating that the remote server cannot receive a response in a timely manner. (New HTTP 1.1)
505 the HTTP Version Not Supported server does Not support the HTTP Version specified in the request. (New HTTP 1.1)


7.4 instance: Access Multiple Search Engines

The following example uses two common status codes except 200: 302 and 404. 302 use the sendRedirect method and 404 use the sendError method.

In this example, the first HTML form is used to select the search engine, search string, and the number of search results displayed on each page. After the form is submitted, Servlet extracts the three variables, constructs the URL containing these variables according to the requirements of the selected search engine, and redirects the user to this URL. If you cannot select a search engine correctly or use other forms to send an unknown search engine name, the system returns a 404 page indicating that the search engine cannot be found.

SearchEngines. java

Note: this Servlet will use the SearchSpec class provided later. The SearchSpec function is to construct URLs suitable for different search engines.
Package hall;

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

Public class SearchEngines extends HttpServlet {
Public void doGet (HttpServletRequest request,
HttpServletResponse response)
Throws ServletException, IOException {
// GetParameter automatically decodes the URL encoded query string. Because we
// Send the query string to another server, so use
// URL encoding by URLEncoder
String searchString =
URLEncoder. encode (request. getParameter ("searchString "));
String numResults =
Request. getParameter ("numResults ");
String searchEngine =
Request. getParameter ("searchEngine ");
SearchSpec [] commonSpecs = SearchSpec. getCommonSpecs ();
For (int I = 0; I <commonSpecs. length; I ++ ){
SearchSpec searchSpec = commonSpecs [I];
If (searchSpec. getName (). equals (searchEngine )){
String url =
Response. encodeURL (searchSpec. makeURL (searchString,
NumResults ));
Response. sendRedirect (url );
Return;
}
}
Response. sendError (response. SC _NOT_FOUND,
"No recognized search engine specified .");
}

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




SearchSpec. java
Package hall;

Class SearchSpec {
Private String name, baseURL, numResultsSuffix;

Private static SearchSpec [] commonSpecs =
{New SearchSpec ("google ",
"Http://www.google.com/search? Q = ",
"& Num = "),
New SearchSpec ("infoseek ",
"Http://infoseek.go.com/Titles? Qt = ",
"& Nh = "),
New SearchSpec ("lycos ",
"Http://lycospro.lycos.com/cgi-bin/pursuit? Query = ",
"& Maxhits = "),
New SearchSpec ("hotbot ",
"Http://www.hotbot.com /? MT = ",
"& DC = ")
};

Public SearchSpec (String name,
String baseURL,
String numResultsSuffix ){
This. name = name;
This. baseURL = baseURL;
This. numResultsSuffix = numResultsSuffix;
}

Public String makeURL (String searchString, String numResults ){
Return (baseURL + searchString + numResultsSuffix + numResults );
}

Public String getName (){
Return (name );
}

Public static SearchSpec [] getCommonSpecs (){
Return (commonSpecs );
}
}




SearchEngines.html

The following is an HTML form that calls the Servlet.
<! Doctype html public "-// W3C // dtd html 4.0 Transitional // EN">
<HTML>
<HEAD>
<TITLE> access multiple search engines </TITLE>
</HEAD>

<Body bgcolor = "# FDF5E6">

<Form action = "/servlet/hall. SearchEngines">
<CENTER>
Search Keyword:
<Input type = "TEXT" NAME = "searchString"> <BR>
Several query results are displayed on each page:
<Input type = "TEXT" NAME = "numResults"
VALUE = 10 SIZE = 3> <BR>
<Input type = "RADIO" NAME = "searchEngine"
VALUE = "google">
Google |
<Input type = "RADIO" NAME = "searchEngine"
VALUE = "infoseek">
Infoseek |
<Input type = "RADIO" NAME = "searchEngine"
VALUE = "lycos">
Lycos |
<Input type = "RADIO" NAME = "searchEngine"
VALUE = "hotbot">
HotBot
<BR>
<Input type = "SUBMIT" VALUE = "Search">
</CENTER>
</FORM>

</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.