Prentice Hall and Sun Microsystems. Personal use only; do not redistribute.
6.1 Specifying Status Codes
125
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 con 
stant 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 equiva 
lent constant in 
HttpServletResponse
 is 
SC_NOT_FOUND
. In version 2.1 of
the servlet specification, there are three exceptions. The constant for code
302 is derived from the HTTP 1.0 message (Moved Temporarily), not the
HTTP 1.1 message (Found), and the constants for codes 307 (Temporary
Redirect) and 416 (Requested Range Not Satisfiable) are missing alto 
gether. Version 2.2 added the constant for 416, but the inconsistencies for
307 and 302 remain. 
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. Just be aware that both of
these methods throw 
IOException
, whereas 
setStatus
 doesn't.
public void sendError(int code, String message)
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. 
public void sendRedirect(String url)
The 
sendRedirect
 method generates a 302 response along 
with a 
Location
 header giving the URL of the new document. 
With servlets version 2.1, this must be an absolute URL. In 
version 2.2, either an absolute or a relative URL is permitted 
and the system automatically translates relative URLs into 
absolute ones before putting them in the 
Location
 header.
Setting a status code does not necessarily mean that you don't need to
return a document. For example, although most servers automatically gener 
ate a small  File Not Found  message for 404 responses, a servlet might want
to customize this response. Remember that if you do send output, you have
to call 
setStatus
 or 
sendError
 first.  
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




 

 

 

 

 Home | About Us | Network | Services | Support | FAQ | Control Panel | Order Online | Sitemap | Contact

jsp web hosting

 

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