在Java Servlet应用程序中为HTTP 201响应设置Location标头的正确方法是什么 [英] What's the proper way to set the Location header for an HTTP 201 response in a Java Servlet application

查看:1232
本文介绍了在Java Servlet应用程序中为HTTP 201响应设置Location标头的正确方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码向客户端发送HTTP 201创建响应:

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);

它通知客户端创建了一个新的东西并且可以在URL找到它 /应用/东西?ID = 42 。问题是这个URL是相对的。这对于JSP来说是完美的,可以写成如下:

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" />" />

哪会产生以下HTML:

Which would produce the following HTML:

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

这是我们想要的网络应用程序。

Which is what we want for web apps.

但我不相信这是我们想要的201响应位置标题。 HTTP规范

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


14.30位置



位置响应标头字段用于将收件人重定向到Request-URI以外的位置完成请求或识别新资源。对于201(已创建)响应,位置是由请求创建的新资源的位置。对于3xx响应,位置应该应该指示服务器自动重定向到资源的首选URI。字段值由单个绝对URI组成。

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

一个例子是:

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


我的问题是如何以适当的方式将servlet的相对URL转换为Location头的绝对URL。

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

我不相信使用:

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

是正确的解决方案。应该有一个生成正确输出的标准方法(以便可以应用URL重写等)。我不想创建一个hack。

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.

推荐答案

只需发送绝对路径即可。 对绝对URI的限制是RFC 2616中的已知缺陷,将在HTTPbis中修复(参见 http://trac.tools.ietf.org/wg/httpbis/trac/ticket/185

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

请注意,RFC 7231 现在包含中的相对URI规范请参阅有关如何处理相对URI的其他答案。

这篇关于在Java Servlet应用程序中为HTTP 201响应设置Location标头的正确方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆