What's the proper way to set the Location header for an HTTP 201 response in a Java Servlet application

les2 picture les2 · Feb 18, 2011 · Viewed 60.4k times · Source

Consider the following code sending an HTTP 201 "Created" response to the client:

    String url = "/app/things?id=42"; // example
    response.setStatus(HttpServletResponse.SC_CREATED);
    response.setContentType("text/plain");
    response.setHeader("Location", url);
    response.getWriter().print(url);

It informs the client that a new "thing" was created and that it can be found at the URL /app/things?id=42. The problem is that this URL is relative. This would be perfect for a JSP, which might be written as follows:

<img src="<c:url value="/things?id=42" />" />

Which would produce the following HTML:

<img src="/app/things?id=42" />

Which is what we want for web apps.

But I don't believe that is what we want for a 201 response Location header. The HTTP spec states:

14.30 Location

The Location response-header field is used to redirect the recipient to a location other than the Request-URI for completion of the request or identification of a new resource. For 201 (Created) responses, the Location is that of the new resource which was created by the request. For 3xx responses, the location SHOULD indicate the server's preferred URI for automatic redirection to the resource. The field value consists of a single absolute URI.

       Location = "Location" ":" absoluteURI

An example is:

       Location: http://www.w3.org/pub/WWW/People.html

My question is how do I translate that relative URL to the abosolute URL for the Location header in the proper way for servlets.

I do NOT believe that using:

request.getServerName() + ":" + request.getServerPort() + url;

Is the correct solution. There should be a standard method that produces the correct output (so that URL rewriting, etc., can be applied). I don't want to create a hack.

Answer

Julian Reschke picture Julian Reschke · Feb 18, 2011

Just send the absolute path. The restriction to an absolute URI is a known defect in RFC 2616 and will be fixed in HTTPbis (see http://trac.tools.ietf.org/wg/httpbis/trac/ticket/185).

Please note that RFC 7231 now includes relative URIs in the spec. See other answers for how to handle relative URIs.