Language Translator

Servlet Request & Response Behaviour

A request from a browser or other client consists
of an HTTP command (usually GET or POST), zero or more request headers (one or
more in HTTP 1.1, since Host is required), a blank line, and, only in the case of
POST requests, some query data. A typical request looks like the following.
GET /servlet/SomeName HTTP/1.1
Host: ...
Header2: ...
...
HeaderN:

When a Web server responds to a request, the response typically consists of a status
line, some response headers, a blank line, and the document. A typical response
looks like this:
HTTP/1.1 200 OK
Content-Type: text/html
Header2: ...
...
HeaderN: ...



...

...


The status line consists of the HTTP version (HTTP/1.1 in the preceding example),
a status code (an integer; 200 in the example), and a very short message corresponding
to the status code (OK in the example). In most cases, 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 various
status codes essentially indicate failure or redirection (and thus either don’t include a
document or include only a short error-message document).

Servlets can perform a variety of important 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 HTML file; tell
the user that a password is required to access the document; and so forth. This chapter
summarizes the most important status codes and describes what can be accomplished
with them; the following chapter discusses the response headers.


Specifying Status Codes

As just described, 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 a servlet needs to do is
to set the status code. A code of 200 is set automatically, so servlets don’t usually need
to specify a status code at all. When they do want to, they use response.setStatus,
response.sendRedirect, or response.sendError.


Setting Arbitrary Status Codes: setStatus

When you want to set an arbitrary status code, do so with the setStatus method of
HttpServletResponse. If your response includes a special status code and a document,
be sure to call setStatus before actually returning any of the content with
the PrintWriter. The reason is that an HTTP response consists of the status line,
one or more headers, a blank line, and the actual document, in that order. Servlets do
not necessarily buffer the document, so you have to either set the status code before
using the PrintWriter or carefully check that the buffer hasn’t been flushed and
content actually sent to the browser

The setStatus method takes an int (the status code) as an argument, but
instead of using explicit numbers, for readability and to avoid typos, use the constants
defined in HttpServletResponse. The name of each constant is derived
from the standard HTTP 1.1 message for each constant, all upper case 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 is one minor exception, however: the constant for code 302
is derived from the message defined by HTTP 1.0 (Moved Temporarily), not the
HTTP 1.1 message (Found).

Setting 302 and 404 Status Codes:
sendRedirect and sendError

Although the general method of setting status codes is simply to call
response.setStatus(int), there are two common cases for which a shortcut
method in HttpServletResponse is provided. Just be aware that both of these
methods throw IOException, whereas setStatus does not. Since the doGet and
doPost methods already throw IOException, this difference only matters if you
pass the response object to another method.

public void sendRedirect(String url)
The 302 status code directs the browser to connect to a new location.
The sendRedirect method generates a 302 response along with a
Location header giving the URL of the new document. Either an
absolute or a relative URL is permitted; the system automatically
translates relative URLs into absolute ones before putting them in the
Location header.

public void sendError(int code, String message)
The 404 status code is used when no document is found on the server.
The sendError method sends a status code (usually 404) along with
a short message that is automatically formatted inside an HTML
document and sent to the client.
Setting a status code does not necessarily mean that you omit the document. For
example, although most servers automatically generate a small File Not Found message
for 404 responses, a servlet might want to customize this response. Again,
remember that if you do send output, you have to call setStatus or sendError
first.

HTTP 1.1 Status Codes

In this section we describe the most important status codes available for use in servlets
talking to HTTP 1.1 clients, along with the standard message associated with
each code. A good understanding of these codes can dramatically increase the capabilities
of your servlets, so you should at least skim the descriptions to see what
options are at your disposal. You can come back for details when you are ready to use
the capabilities.

The complete HTTP 1.1 specification is given in RFC 2616. In general, you can
access RFCs online by going to http://www.rfc-editor.org/ and following the links to
the latest RFC archive sites, but since this one came from the World Wide Web Consortium,
you can just go to http://www.w3.org/Protocols/. Codes that are new in
HTTP 1.1 are noted since some browsers support only HTTP 1.0. You should only
send the new codes to clients that support HTTP 1.1, as verified by checking
request.getRequestProtocol.

The rest of this section describes the specific status codes available in HTTP 1.1.
These codes fall into five general categories:
• 100–199
Codes in the 100s are informational, indicating that the client should
respond with some other action.
• 200–299
Values in the 200s signify that the request was successful.
• 300–399
Values in the 300s are used for files that have moved and usually
include a Location header indicating the new address.
• 400–499
Values in the 400s indicate an error by the client.
• 500–599
Codes in the 500s signify an error by the server.

The constants in HttpServletResponse that represent the various codes
are derived from the standard messages associated with the codes. In servlets, you
usually refer to status codes only by means of these constants. For example, you
would use response.setStatus(response.SC_NO_CONTENT) rather than
response.setStatus(204), since the latter is unclear to readers and is prone to
typographical errors. However, you should note that servers are allowed to vary the
messages slightly, and clients pay attention only to the numeric value. So, for example,
you might see a server return a status line of HTTP/1.1 200 Document
Follows instead of HTTP/1.1 200 OK.

100 (Continue)
If the server receives an Expect request header with a value of
100-continue, it means that the client is asking if it can send an attached
document in a follow-up request. In such a case, the server should either
respond with status 100 (SC_CONTINUE) to tell the client to go ahead or use
417 (SC_EXPECTATION_FAILED) to tell the browser it won’t accept the document.
This status code is new in HTTP 1.1.
200 (OK)
A value of 200 (SC_OK) means that everything is fine; the document follows for
GET and POST requests. This status is the default for servlets; if you don’t use
setStatus, you’ll get 200.
202 (Accepted)
A value of 202 (SC_ACCEPTED) tells the client that the request is being acted
upon but processing is not yet complete.
204 (No Content)
A status code of 204 (SC_NO_CONTENT) stipulates that the browser should
continue to display the previous document because no new document is available.
This behavior is useful if the user periodically reloads a page by pressing
the Reload button and you can determine that the previous page is already
up-to-date.
205 (Reset Content)
A value of 205 (SC_RESET_CONTENT) means that there is no new document
but the browser should reset the document view. Thus, this status code is used
to instruct browsers to clear form fields. It is new in HTTP 1.1.
301 (Moved Permanently)
The 301 (SC_MOVED_PERMANENTLY) status indicates that the requested document
is elsewhere; the new URL for the document is given in the Location
response header. Browsers should automatically follow the link to the new
URL.
302 (Found)
This value is similar to 301, except that in principle the URL given by the
Location header should be interpreted as a temporary replacement, not a
permanent one. In practice, most browsers treat 301 and 302 identically. Note:
in HTTP 1.0, the message was Moved Temporarily instead of Found, and
the constant in HttpServletResponse is SC_MOVED_TEMPORARILY, not
the expected SC_FOUND.

No comments:

Post a Comment