| ★ wanayoo — archive 1999 http://java.webdeveloper.com/tutorials/JSP/part08/ | Nouvelle recherche | Portail wanayoo |
![]() | ||||||||||||||||
Tutorials :
Server-Side Web Applications Using Servlets and JSP :
|
||||||||||||||||
| Contents |
| Specifying HTTP Response Headers |
| Common Response Headers and their Meaning |
| Example: Automatically Reloading Pages as Content Changes |
Location header, and a 401 (Unauthorized)
code must include an accompanying WWW-Authenticate header.
However, specifying headers can play a useful role even when no unusual status code is set. Response headers can be used to specify cookies, to supply the modification date (for caching), to instruct the browser to reload the page after a designated interval, to say how long the file is so that persistent HTTP connections can be used, and many other tasks.
The most general way to specify headers is by the setHeader
method of HttpServletResponse, which takes two strings: the header name
and the header value. Like setting the status codes, this
must be done before any document content is sent.
There are also two specialized methods to set headers that contain
dates (setDateHeader) and integers (setIntHeader). The first saves you
the trouble of translating a Java date in milliseconds since the epoch
(as returned by System.currentTimeMillis or the getTime method applied
to a Date object) into a GMT time string. The second spares you
the minor inconvenience of converting an int to a String.
Rather than setting a header outright, you can add a new header, in case a header
with that name already exists. Use addHeader,
addDateHeader, and addIntHeader for this. If it really
matters to you whether a specific header has already been set, use
containsHeader to check.
Finally, HttpServletResponse also supplies a number of convenience methods
for specifying common headers.
setContentType method sets the
Content-Type header, and is used by the majority of servlets.
setContentLength method sets the Content-Length header,
useful if the browser supports persistent (keep-alive) HTTP connections.
addCookie method sets a cookie (there is no corresponding setCookie,
since it is normal to have multiple Set-Cookie lines).
sendRedirect method sets the Location header
as well as setting the status code to 302.
This tutorial is now available as a book: Core Servlets and JavaServer Pages by Marty Hall, published by Sun Microsystems Press. Read all about it at CoreServlets.com
|
