JSP HTTP reply status

Source: Internet
Author: User
Tags constant contains continue header html form implement variables query
Js

7.1 Status Code Overview

When a Web server responds to a request from a browser or other client, its answer typically consists of a status line, several answer headers, a blank line, and a content document. Here is one of the simplest answers:
http/1.1 OK
Content-type:text/plain

Hello World




The status line contains the HTTP version, status code, and a brief description of the status code. In most cases, all answer headers except content-type are optional. However, Content-type is required, which describes the MIME type of the subsequent document. Although most answers contain a single document, there are some that are not included, such as a response to a head request that never comes with a document. There are many status codes that are actually used to identify a failed request that does not contain a document (or contains only a brief error message description).

The servlet can use the status code to implement many functions. For example, you can redirect users to another Web site, and you can indicate that the following document is a picture, PDF file, or HTML file, and you can tell the user that you must provide a password to access the document; In this section we will discuss in detail the meaning of the various status codes and what we can do with the code.

7.2 Setting the status code

As mentioned earlier, the HTTP answer status line contains the HTTP version, status code, and corresponding state information. Because the state information is directly related to the status Code, and the HTTP version is determined by the server, there is only one status code that needs to be set by the servlet.

The servlet setting status code generally uses the HttpServletResponse SetStatus method. The parameter of the SetStatus method is an integer (that is, the status code), but in order for the code to be more readable, you can use constants defined in HttpServletResponse to avoid using integers directly. These constants are named according to the standard state information in HTTP 1.1, all names are prefixed with the SC prefix (the Status code abbreviation) and uppercase, and the spaces are underlined. In other words, the state information corresponding to the status code 404 is "Not Found", and the corresponding constant in HttpServletResponse is named Sc_not_found. But there are two exceptions: the constant corresponding to the status code 302 is named after HTTP 1.0, and 307 has no corresponding constant.

Setting the status code does not always mean that the document will not be returned. For example, although most servers return a 404 response with a simple "File not Found" message, the servlet can also customize this response. However, a custom response should call Response.setstatus before any content is sent through PrintWriter.

While setting the status code generally uses the response.setstauts (int) method, for simplicity, HttpServletResponse provides a dedicated method for two common scenarios: the Senderror method generates a 404 response, Generates a short HTML error message document at the same time; the Sendredirect method generates a 302 answer while indicating the URL of the new document in the location header.

7.3 HTTP 1.1 Status code and what it means

The following table shows the common HTTP 1.1 status codes along with their corresponding state information and meanings.

You should be cautious about using state codes that only have HTTP 1.1 support, because many browsers can only support HTTP 1.0. If you use HTTP 1.1-specific status codes, it's a good idea to check the HTTP version number of the request (via the HttpServletRequest Getprotocol method). Status Code state information meaning
The initial request of Continue has been accepted and the customer should continue to send the remainder of the request. (HTTP 1.1 new)
The switching protocols server converts requests to a different protocol (HTTP 1.1 new)
All OK, the answer document for Get and post requests follows. If you do not set the status code setstatus, the servlet defaults to the 202 status code.
The 201 Created Server has created the document, and the location header gives its URL.
The accepted has accepted the request, but the processing has not yet been completed.
203 Non-authoritative Information The document has returned normally, but some of the answer headers may be incorrect because a copy of the document is being used (HTTP 1.1 new).
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 periodically refreshes the page and the servlet can determine that the user's document is new enough.
205 The Reset content does not have new content, but the browser should reset what it displays. Used to force the browser to clear form input (HTTP 1.1 new).
206 Partial Content Customer sent a GET request with a range header, and the server completed it (HTTP 1.1 new).
Multiple choices customer-requested documents can be found in multiple locations that are already listed in the returned document. If the server wants to make a preference, it should be indicated in the location answer header.
Moved permanently customer requested document elsewhere, the new URL is given in the location header, and the browser should automatically access the new URL.
The 302 Found is similar to 301, but the new URL should be treated as a temporary alternative, not permanent. Note that the corresponding state information in the HTTP1.0 is "moved temporatily" and that the corresponding 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 useful status code. To do this, the servlet provides a dedicated method, namely Sendredirect. Use Response.sendredirect (URL) than using Response.setstatus (response. sc_moved_temporarily) and Response.setheader ("Location", url) better. This is because:

First, the code is more concise.
Second, using Sendredirect,servlet automatically constructs a page that contains new links (for older browsers that cannot be redirected automatically).
Finally, Sendredirect can process relative URLs and automatically convert them to absolute URLs.
Note that this status code can sometimes be replaced with 301. For example, if the browser incorrectly requests Http://host/~user (a trailing slash is missing), some servers return 301, and some return 302.

Strictly speaking, we can only assume that the browser will automatically redirect only if the original request is get. Please see 307.

303 The other is similar to 301/302, except that if the original request was post,location the redirected target document specified by the header should be fetched through get (HTTP 1.1 new).
The 304 not Modified client has buffered documents and makes a conditional request (typically providing a if-modified-since header that indicates that the customer only wants to update the document for a specified date). The server tells the customer that the previously buffered document can continue to be used.
305 Use proxy Client-requested documentation should be extracted via the proxy server indicated by the location header (HTTP 1.1 new).
307 Temporary Redirect and 302 (Found) are the same. Many browsers incorrectly respond to 302 responses for redirection, even if the original request is post, even if it is actually only redirected when the POST request is answered at 303. For this reason, HTTP 1.1 has been added 307 to further clear the locale code: when a 303 reply occurs, the browser can follow the redirected get and post requests, and if 307 answers, the browser can only follow the redirection of the got request.
Note that the HttpServletResponse does not provide the corresponding constant for the status code. (HTTP 1.1 new)

Bad request syntax error occurred.
401 Unauthorized customer is trying to access a password-protected page without authorization. A www-authenticate header is included in the answer, the browser displays the user name/password dialog Accordingly, and then makes the request again after filling in the appropriate authorization header.
403 Forbidden Resource is not available. The server understands the customer's request, but refuses to process it. This is usually caused by a permission setting on a file or directory on the server.
404 Not Found Cannot find a resource at the specified location. This is also a commonly used answer, HttpServletResponse specifically provides the appropriate method: Senderror (Message).
The 405 method does not allowed request methods (GET, POST, head, DELETE, put, Trace, and so on) do not apply to the specified resource. (HTTP 1.1 new)
406 not acceptable the specified resource has been found, but its MIME type is incompatible with the client specified in the Accpet header (HTTP 1.1 new).
The 407 proxy authentication Required is similar to 401, which means that the customer must first be authorized by the proxy server. (HTTP 1.1 new)
408 Request Timeout The customer has not made any requests for the duration of the server license. Customers can repeat the same request at a later time. (HTTP 1.1 new)
409 Conflict are usually associated with put requests. The request cannot succeed because the request and the current state of the resource are conflicting. (HTTP 1.1 new)
410 Gone The requested document is no longer available and the server does not know which address should be redirected to. It differs from 404 in that the return of 407 indicates that the document left the specified location permanently, while 404 indicates that the document is not available because of an unknown reason. (HTTP 1.1 new)
411 Length Required The server cannot process the request unless the customer sends a content-length header. (HTTP 1.1 new)
Some prerequisites specified in the 412 precondition Failed request header failed (HTTP 1.1 new).
413 Request Entity Too Large the size of the target document exceeds the size that the server is currently willing to handle. If the server considers itself able to process the request later, it should provide a Retry-after header (HTTP 1.1 new).
414 Request Uri Too long URI (HTTP 1.1 new).
The 416 requested range not satisfiable server does not meet the range header specified by the customer in the request. (HTTP 1.1 new)
Internal server Error Servers encountered unexpected circumstances, unable to complete the customer's request.
The 501 not implemented server does not support the functionality required to implement the request. For example, the customer issued a put request that the server does not support.
502 Bad Gateway server, as a gateway or proxy, accesses the next server in order to complete the request, but the server returns an illegal reply.
503 Service unavailable Server failed to answer due to maintenance or overload. For example, a servlet might return 503 if the database connection pool is full. The server can provide a retry-after header when it returns 503.
The 504 Gateway Timeout is used by a server acting as a proxy or gateway, indicating that an answer cannot be received from a remote server in a timely manner. (HTTP 1.1 new)
505 HTTP version not supported server does not support HTTP versions as specified in the request. (HTTP 1.1 new)


7.4 Example: access to multiple search engines

The following example uses two other common state codes except 200:302 and 404. 302 through the Sendredirect method setting, 404 is set by the Senderror method.

In this example, the first HTML form that appears is used to select search engines, search strings, and the number of search results displayed per page. After the form is submitted, the servlet extracts the three variables, constructs the URL that contains the variables according to the search engine's requirements, and then redirects the user to the URL. If the user does not select the search engine correctly, or use another form to send a name of a search engine that you do not know, return a 404 page that prompts the search engine to find it.

Searchengines.java

Note: This servlet uses the Searchspec class given later, and Searchspec's 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 URL-encoded query strings. As we
To send the query string to another server, use the
Urlencoder for URL encoding
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 invokes the above 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 keywords:
<input type= "TEXT" Name= "searchstring" > <BR>
Display several query results per 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.