Prentice Hall and Sun Microsystems. Personal use only; do not redistribute.
124
Chapter 6 Generating the Server Response: HTTP Status Codes
can be accomplished with them, and the following chapter discusses the
response headers.
6.1 Specifying Status Codes
As just described, the HTTP response status line consists of an HTTP ver
sion, 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. The way to do this is
by 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 via the
PrintWriter
. That's
because an HTTP response consists of the status line, one or more headers,
a blank line, and the actual document, in that order. The headers can
appear in any order, and servlets buffer the headers and send them all at
once, so it is legal to set the status code (part of the first line returned) even
after setting headers. But servlets do not necessarily buffer the document
itself, since users might want to see partial results for long pages. In version
2.1 of the servlet specification, the
PrintWriter
output is not buffered at
all, so the first time you use the
PrintWriter
, it is too late to go back and
set headers. In version 2.2, servlet engines are permitted to partially buffer
the output, but the size of the buffer is left unspecified. You can use the
getBufferSize
method of
HttpServletResponse
to determine the size,
or use
setBufferSize
to specify it. In version 2.2 with buffering enabled,
you can set status codes until the buffer fills up and is actually sent to the
client. If you aren't sure if the buffer has been sent, you can use the
isCom
mitted
method to check.
Core Approach
Be sure to set status codes before sending any document content to the
client.
Second edition of this book: www.coreservlets.com; Sequel: www.moreservlets.com.
Servlet and JSP training courses by book's author: courses.coreservlets.com.
footer
Our partners:
PHP: Hypertext Preprocessor Best Web Hosting
Java Web Hosting
Jsp Web Hosting
Cheapest Web Hosting
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved