Status Codes
Until now, our servlet examples have not set HTTP response status codes. We’ve been taking advantage of the fact that if a servlet doesn’t specifically set the status code, the server steps in and sets its value to the default 200 “OK” status code. That’s a useful convenience when we are returning normal successful responses. However, by using status codes, a servlet can do more with its response. For example, it can redirect a request or report a problem.
The most common status code numbers are defined as mnemonic constants
(public
final
static
int
fields) in the
HttpServletResponse
class. A few of these are
listed in Table 5.1. The full list is available in
Appendix C.
Table 5-1. HTTP Status Codes
Mnemonic Constant |
Code |
Default Message |
Meaning |
---|---|---|---|
SC_OK |
200 |
OK |
The client’s request was successful, and the server’s response contains the requested data. This is the default status code. |
SC_NO_CONTENT |
204 |
No Content |
The request succeeded, but there was no new response body to return. Browsers receiving this code should retain their current document view. This is a useful code for a servlet to use when it accepts data from a form but wants the browser view to stay at the form, as it avoids the “Document contains no data” error message. |
SC_MOVED_PERMANENTLY |
301 |
Moved Permanently |
The requested resource has permanently moved to a new location. Future references should use the new URL in requests. The
new location is given by the |
Get Java Servlet Programming now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.