Setting the HTTP status code

As well as sending the Servlet output to a given request, it is sometimes necessary to set a status code. An HTTP status code— sometimes called a response code— effectively tells the client what the output represents. Or in other words, it indicates the status of the requeset: successful, page not found, access denied etc.

By default, a Servlet will send send a status code "OK". Most of the time, when your Servlet has output the requested page, the default response code is the write code to send.

Occasionally, you may need to set a different status code on the response from your Servlet. To set a different HTTP status code from your Servlet, call the following method on the HttpServletResponse object passed in to your server:

res.setStatus(nnn);

where nnn is a valid HTTP status code. We'll discuss some common HTTP status codes below.

When to set the status code

In general, you should set the status code before sending any output. This is because the status code always comes before any output in the data returned to the client. In practice, if your Servlet runner is buffering output, you may actually "get away with it" if you set the status code a bit later. But setting the status code after sending output isn't reliable or recommended.

Always send output

Before we look at some actual status codes, it's worth mentioning that if you set a non-default status code, you should generally send some appropriate output from your Servlet as well. The reason for this is that if you don't, must Servlet runners send some default "system" message corresponding to the status code you set. The message may include details about your environment (such as the web server/Servlet runner version) that you don't necessarily want the outside world to know about.

Status code constants

HTTP status codes are numeric, but for each there is generally a corresponding constant on HttpServletResponse that you can use. The constants all begin with SC_, as in the list below. So, for example, to send a status of 403 ("forbidden"), you can call:

res.setStatus(HttpServletResponse.SC_FORBIDDEN);

Common status codes

The following are the most useful HTTP status codes that might be sent from a Servlet. For a more complete list, see the HTTP protocol, and the Wikipedia entry on HTTP status codes. Some of the codes not included in this list are either rarely used generally, or make very little sense from the point of view of a Servlet.

Status code 301 SC_MOVED_PERMANENTLY

Indicates a permanent redirection. Sending this code tells the client that "the location of this resource has now changed", and that the client should use a new URL in the future. If you send this code, you should also set the Location response header with the new location:

String newURL = res.encodeRedirectURL("...");
res.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
res.setHeader("Location", newURL);

At least some search engines appear to take notice of this redirection, but of course some may not. Note the call to encodeRedirectURL()1, which will make sure that any request parameters are preserved.

Status code 307 SC_TEMPORARY_REDIRECT

This code is sometimes called a temporary redirect. Like the previous code, it indicates that the resource is at a different URL. A browser should instead request the provided URL, but, for example, a search engine shouldn't permanently update its database with the new URL. A more convenient way of sending this code is to use the special method on HttpServletResponse:

String newURL = res.encodeRedirectURL("...");
res.sendRedirect(newURL);
Status code 400 SC_BAD_REQUEST

This code is useful if you parse parts of the URL or requeset parameters in order to decide on your Servlet's response. If the client sends parameters that are invalid in some way, you can send this response code.

Status code 403 SC_FORBIDDEN

This code may be useful for more "serious" denials of requests, for example if the user is in the wrong territory. Usually, for a "not logged in" message to the user, you would want to return a normal, "friendly" response.

Status code 404 SC_NOT_FOUND

Useful if your Servlet is dynamically interpreting the URL and returning page content accordingly. On the other hand, when the user requests a normal static page that isn't found (i.e. when not going through your Servlet), most web servers such as Apache will automatically return the 404 response code, plus a default or customised response page.

Status code 405 SC_METHOD_NOT_ALLOWED

You could use this if, for example, you wanted to force the client to issue either GET or POST requests by returning this status code from the disallowed method (doGet() or doPost()):

public void doPost(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {
  res.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
  res.getWriter().println("<html><body><p>Use "
	+ "GET instead!</p></body></html>");
}
Status code 418 I'm a teapot (TeapotHttpConstants.STATUS_CODE_TEAPOT)

This code is most commonly used as part of the Java Teapot Embedded JTETM framework. If you are not using this framework, you can generally ignore status code 418. There is currently no constant in HttpServletResponse corresponding to this code, so you should either encode it directly or use TeapotHttpConstants.STATUS_CODE_TEAPOT. For more details, see RFC 2324.

Status code 500 SC_INTERNAL_SERVER_ERROR

You could set this, for example, if you catch an exception during your Servlet code. It's debatable whether sending this code is "giving the client too much information".


1. The version encodeRedirectUrl (note the small latters on Url) is a hangover from early versions of the Servlet framework and is now deprecated. Use the capitalised version encodeRedirectURL().


If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.

Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.