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


consider following code sending http 201 "created" response 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 client new "thing" created , can found @ url /app/things?id=42. problem url relative. perfect jsp, might written follows:

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

which produce following html:

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

which want web apps.

but don't believe want 201 response location header. http spec states:

14.30 location

the location response-header field used redirect recipient location other request-uri completion of request or identification of new resource. 201 (created) responses, location of new resource created request. 3xx responses, location should indicate server's preferred uri automatic redirection resource. field value consists of single absolute uri.

       location = "location" ":" absoluteuri 

an example is:

       location: http://www.w3.org/pub/www/people.html 

my question how translate relative url abosolute url location header in proper way servlets.

i not believe using:

request.getservername() + ":" + request.getserverport() + url; 

is correct solution. there should standard method produces correct output (so url rewriting, etc., can applied). don't want create hack.

just send absolute path. the restriction absolute uri known defect in rfc 2616 , fixed in httpbis (see http://trac.tools.ietf.org/wg/httpbis/trac/ticket/185).

please note rfc 7231 now includes relative uris in the spec. see other answers how handle relative uris.


Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -