Book Home Java Servlet Programming Search this book

5.5. 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 (publicfinalstaticint fields) in the HttpServletResponse class. A few of these are listed in Table 5-1. The full list is available in Appendix C, "HTTP Status Codes".

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 Location header. Most browsers automatically access the new location.

SC_MOVED_TEMPORARILY

302

Moved Temporarily

The requested resource has temporarily moved to another location, but future references should still use the original URL to access the resource. The new location is given by the Location header. Most browsers automatically access the new location.

SC_UNAUTHORIZED

401

Unauthorized

The request lacked proper authorization. Used in conjunction with the WWW-Authenticate and Authorization headers.

SC_NOT_FOUND

404

Not Found

The requested resource was not found or is not available.

SC_INTERNAL_SERVER_ERROR

500

Internal Server Error

An unexpected error occurred inside the server that prevented it from fulfilling the request.

SC_NOT_IMPLEMENTED

501

Not Implemented

The server does not support the functionality needed to fulfill the request.

SC_SERVICE_UNAVAILABLE

503

Service Unavailable

The service (server) is temporarily unavailable but should be restored in the future. If the server knows when it will be available again, a Retry-After header may also be supplied.

5.5.1. Setting a Status Code

A servlet can use setStatus() to set a response status code:

public void HttpServletResponse.setStatus(int sc)
public void HttpServletResponse.setStatus(int sc, String sm)

Both of these methods set the HTTP status code to the given value. The code can be specified as a number or with one of the SC_XXX codes defined within Http-ServletResponse. With the single-argument version of the method, the reason phrase is set to the default message for the given status code. The two-argument version allows you to specify an alternate message. Remember, the setStatus() method should be called before your servlet returns any of its response body.

If a servlet sets a status code that indicates an error during the handling of the request, it can call sendError() instead of setStatus():

public void HttpServletResponse.sendError(int sc) 
public void HttpServletResponse.sendError(int sc, String sm)

A server may give the sendError() method different treatment than setStatus(). When the two-argument version of the method is used, the status message parameter may be used to set an alternate reason phrase or it may be used directly in the body of the response, depending on the server's implementation.

5.5.2. Improving ViewFile Using Status Codes

So far, we haven't bothered calling any of these methods to set a response's status code. We've simply relied on the fact that the status code defaults to SC_OK. But there are times when a servlet needs to return a response that doesn't have the SC_OK status code--when the response does not contain the requested data. As an example, think back to how the ViewFile servlet in Chapter 4, "Retrieving Information", handled the FileNotFoundException:

// Return the file
try {
  ServletUtils.returnFile(file, out);
}
catch (FileNotFoundException e) {
  out.println("File not found");
}

Without setting a status code, the best this servlet can do is write out an explanation of the problem, ironically sending the explanation as part of a page that is supposed to contain the file's contents. With status codes, however, it can do exactly what Sun's FileServlet does: set the response code to SC_NOT_FOUND to indicate that the requested file was not found and cannot be returned. Here's the improved version:

// Return the file
try {
  ServletUtils.returnFile(file, out);
}
catch (FileNotFoundException e) {
  res.sendError(res.SC_NOT_FOUND);
}

The full effect of a sendError() call is server dependent, but for the Java Web Server this call generates the server's own "404 Not Found" page, complete with Duke's picture (as shown in Figure 5-2). Note that this page is indistinguishable from every other Java Web Server "404 Not Found" page. The call to sendError() also results in a note in the server's access log that the file could not be found.

figure

Figure 5-2. The Java Web Server "404 Not Found" page



Library Navigation Links

Copyright © 2001 O'Reilly & Associates. All rights reserved.