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.
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 .