您的位置:寻梦网首页编程乐园JAVA 天地Servlet 专辑Servlet and JSP Tutorial
Setting HTTP Status Codes

  1. Overview
  2. Specifying Status Codes
  3. HTTP 1.1 Status Codes and Their Meaning
  1. Example: Search Engine Front End
  2. Servlet and JSP Tutorial: Top
  3. Servlet and JSP Training Courses On-site at your company or at public venues.

Note: Chapter 6 of Core Servlets and JavaServer Pages contains much more detailed and up to date information on this topic. The full text is now available online in PDF for free access.

1. Overview

When a Web server responds to a request from a browser or other Web client, the response typically consists of a status line, some response headers, a blank line, and the document. Here is a minimal example:
HTTP/1.1 200 OK
Content-Type: text/plain

Hello World
The status line consists of the HTTP version, an integer that is interpreted as a status code, and a very short message corresponding to the status code. In most cases, all of the headers are optional except for Content-Type, which specifies the MIME type of the document that follows. Although most responses contain a document, some don't. For example, responses to HEAD requests should never include a document, and there are a variety of status codes that essentially indicate failure, and either don't include a document or only include a short "error message document".

Servlets can perform a variety of tasks by manipulating the status line and the response headers. For example, they can forward the user to other sites; indicate that the attached document is an image, Adobe Acrobat file, or (most commonly) HTML file; tell the user that a password is required to access the document; and so forth. This section will discuss the various different status codes and what can be accomplished with them, while the following section will discuss the response headers.

2. Specifying Status Codes

As described above, the HTTP response status line consists of an HTTP version, a status code, and an associated message. Since the message is directly associated with the status code and the HTTP version is determined by the server, all the servlet needs to do is to set the status code. The way to do that is by the setStatus method of HttpServletResponse. The setStatus method takes an int (the status code) as an argument, but instead of using explicit numbers, it is clearer and more reliable to use the constants defined in HttpServletResponse. The name of each constant is derived from the standard HTTP 1.1 message for each constant, all uppercase with a prefix of SC (for Status Code) and spaces changed to underscores. Thus, since the message for 404 is Not Found, the equivalent constant in HttpServletResponse is SC_NOT_FOUND. There are two exceptions however. For some odd reason the constant for code 302 is derived from the HTTP 1.0 message, not the HTTP 1.1 message, and the constant for code 307 is missing altogether.

Setting the status code does not always mean that you don't need to return a document. For example, although most servers will generate a small "File Not Found" message for 404 responses, a servlet might want to customize this response. However, if you do this, you need to be sure to call response.setStatus before sending any content via the PrintWriter.

Although the general method of setting status codes is simply to call response.setStatus(int), there are two common cases where a shortcut method in HttpServletResponse is provided. The sendError method generates a 404 response along with a short message formatted inside an HTML document. And the sendRedirect method generates a 302 response along with a Location header indicating the URL of the new document.

3. HTTP 1.1 Status Codes and Their Meaning

Following is a list of all the available HTTP 1.1 status codes, along with their associated message and interpretation. You should be cautious in using the status codes that are available only in HTTP 1.1, since many browsers still only support HTTP 1.0. If you do use status codes specific to HTTP 1.1, in most cases you want to either explicitly check the HTTP version of the request (via the getProtocol method of the HttpServletRequest) or reserve it for situations when no HTTP 1.0 status code would be particularly meaningful to the client anyhow.

Status Code Associated Message Meaning
100 Continue Continue with partial request. (New in HTTP 1.1)
101 Switching Protocols Server will comply with Upgrade header and change to different protocol. (New in HTTP 1.1)
200 OK Everything's fine; document follows for GET and POST requests. This is the default for servlets; if you don't use setStatus, you'll get this.
201 Created Server created a document; the Location header indicates its URL.
202 Accepted Request is being acted upon, but processing is not completed.
203 Non-Authoritative Information Document is being returned normally, but some of the response headers might be incorrect since a document copy is being used. (New in HTTP 1.1)
204 No Content No new document; browser should continue to display previous document. This is a useful if the user periodically reloads a page and you can determine that the previous page is already up to date. However, this does not work for pages that are automatically reloaded via the Refresh response header or the equivalent <META HTTP-EQUIV="Refresh" ...> header, since returning this status code stops future reloading. JavaScript-based automatic reloading could still work in such a case, though.
205 Reset Content No new document, but browser should reset document view. Used to force browser to clear CGI form fields. (New in HTTP 1.1)
206 Partial Content Client sent a partial request with a Range header, and server has fulfilled it. (New in HTTP 1.1)
300 Multiple Choices Document requested can be found several places; they'll be listed in the returned document. If server has a preferred choice, it should be listed in the Location response header.
301 Moved Permanently Requested document is elsewhere, and the URL for it is given in the Location response header. Browsers should automatically follow the link to the new URL.
302 Found Similar to 301, except that the new URL should be interpreted as a temporary replacement, not a permanent one. Note: the message was "Moved Temporarily" in HTTP 1.0, and the constant in HttpServletResponse is SC_MOVED_TEMPORARILY, not SC_FOUND.Very useful header, since browsers automatically follow the link to the new URL. This status code is so useful that there is a special method for it, sendRedirect. Using response.sendRedirect(url) has a couple of advantages over doing response.setStatus(response.SC_MOVED_TEMPORARILY) and response.setHeader("Location", url). First, it is easier. Second, with sendRedirect, the servlet automatically builds a page containing the link (to show to older browsers that don't automatically follow redirects). Finally, sendRedirect can handle relative URLs, automatically translating them to absolute ones.

Note that this status code is sometimes used interchangeably with 301. For example, if you erroneously ask for http://host/~user (missing the trailing slash), some servers will send 301 and others will send 302.

Technically, browsers are only supposed to automatically follow the redirection if the original request was GET. See the 307 header for details.

303 See Other Like 301/302, except that if the original request was POST, the redirected document (given in the Location header) should be retrieved via GET. (New in HTTP 1.1)
304 Not Modified Client has a cached document and performed a conditional request (usually by supplying an If-Modified-Since header indicating that it only wants documents newer than a specified date). Server wants to tell client that the old, cached document should still be used.
305 Use Proxy Requested document should be retrieved via proxy listed in Location header. (New in HTTP 1.1)
307 Temporary Redirect This is identical to 302 ("Found" or "Temporarily Moved"). It was added to HTTP 1.1 since many browsers erroneously followed the redirection on a 302 response even if the original message was a POST, even though it really ought to have followed the redirection of a POST request only on a 303 response. This response is intended to be unambigously clear: follow redirected GET and POST requests in the case of 303 responses, only follow the redirection for GET requests in the case of 307 responses. Note: for some reason there is no constant in HttpServletResponse corresponding to this status code. (New in HTTP 1.1)
400 Bad Request Bad syntax in the request.
401 Unauthorized Client tried to access password-protected page without proper authorization. Response should include a WWW-Authenticate header that the browser would use to pop up a username/password dialog box, which then comes back via the Authorization header.
403 Forbidden Resource is not available, regardless of authorization. Often the result of bad file or directory permissions on the server.
404 Not Found No resource could be found at that address. This is the standard "no such page" response. This is such a common and useful response that there is a special method for it in HttpServletResponse: sendError(message). The advantage of sendError over setStatus is that, with sendError, the server automatically generates an error page showing the error message.
405 Method Not Allowed The request method (GET, POST, HEAD, DELETE, PUT, TRACE, etc.) was not allowed for this particular resource. (New in HTTP 1.1)
406 Not Acceptable Resource indicated generates a MIME type incompatible with that specified by the client via its Accept header. (New in HTTP 1.1)
407 Proxy Authentication Required Similar to 401, but proxy server must return a Proxy-Authenticate header. (New in HTTP 1.1)
408 Request Timeout The client took too long to send the request. (New in HTTP 1.1)
409 Conflict Usually associated with PUT requests; used for situations such as trying to upload an incorrect version of a file. (New in HTTP 1.1)
410 Gone Document is gone; no forwarding address known. Differs from 404 in that the document is is known to be permanently gone in this case, not just unavailable for unknown reasons as with 404. (New in HTTP 1.1)
411 Length Required Server cannot process request unless client sends a Content-Length header. (New in HTTP 1.1)
412 Precondition Failed Some precondition specified in the request headers was false. (New in HTTP 1.1)
413 Request Entity Too Large The requested document is bigger than the server wants to handle now. If the server thinks it can handle it later, it should include a Retry-After header. (New in HTTP 1.1)
414 Request URI Too Long The URI is too long. (New in HTTP 1.1)
415 Unsupported Media Type Request is in an unknown format. (New in HTTP 1.1)
416 Requested Range Not Satisfiable Client included an unsatisfiable Range header in request. (New in HTTP 1.1)
417 Expectation Failed Value in the Expect request header could not be met. (New in HTTP 1.1)
500 Internal Server Error Generic "server is confused" message. It is often the result of CGI programs or (heaven forbid!) servlets that crash or return improperly formatted headers.
501 Not Implemented Server doesn't support functionality to fulfill request. Used, for example, when client issues command like PUT that server doesn't support.
502 Bad Gateway Used by servers that act as proxies or gateways; indicates that initial server got a bad response from the remote server.
503 Service Unavailable Server cannot respond due to maintenance or overloading. For example, a servlet might return this header if some thread or database connection pool is currently full. Server can supply a Retry-After header.
504 Gateway Timeout Used by servers that act as proxies or gateways; indicates that initial server didn't get a response from the remote server in time. (New in HTTP 1.1)
505 HTTP Version Not Supported Server doesn't support version of HTTP indicated in request line. (New in HTTP 1.1)

4. Example: Search Engine Front End

Here's an example that makes use of the two most common status codes other than 200: 302 and 404. The 302 code is set via the shorthand sendRedirect method, and 404 is set via sendError.

In this application, an HTML form first displays a page that lets the user choose a search string, the number of results per page, and the search engine to use. When the form is submitted, the servlet extracts those three parameters, constructs a URL with the parameters embedded in a way appropriate to the search engine selected, and redirects the user to that URL. If the user fails to choose a search engine or a different front end sends an unrecognized search engine name, a 404 error page is returned saying that the search engine is missing or unknown.

If you want to try it out yourself, start with the HTML front-end.

4.1 SearchEngines.java (Download source code)

Note: makes use of the SearchSpec class, shown below, which incorporates information on how to construct URLs to perform searches at various search sites.
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 {
    // The URLEncoder changes spaces to "+" signs and other
    // non-alphanumeric characters to "%XY", where XY is the
    // hex value of the ASCII (or ISO Latin-1) character.
    // The getParameter method decodes automatically, but since
    // we're just passing this on to another server, we need to
    // re-encode it.
    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)) {
        // encodeURL is just planning ahead in case this servlet
        // is ever used in an application that does session tracking.
        // If cookies are turned off, session tracking is usually
        // accomplished by URL rewriting, so all URLs returned
        // by servlets should be sent through encodeURL.
        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);
  }
}

4.2 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);
  }
}

4.3 SearchEngines.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
  <TITLE>Searching the Web</TITLE>
</HEAD>

<BODY BGCOLOR="#FDF5E6">
<H1 ALIGN="CENTER">Searching the Web</H1>

<FORM ACTION="/servlet/hall.SearchEngines">
  <CENTER>
    Search String: 
    <INPUT TYPE="TEXT" NAME="searchString"><BR>
    Results to Show 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>

4.4 Initial Front End

Initial front end.

4.5 Search Result

Search result.