谁能建议我在以下两种方式中使用 REST 重定向 URL 的最佳方法:
1. httpResponse.sendRedirect("URL");
2. Response.temporaryRedirect(new URI("path"));
最佳答案
有几种类型的重定向
根据RFC 7231 ,目前对HTTP/1.1的语义和内容的引用,有several types of redirects .他们都是
Redirects that indicate the resource might be available at a different URI, as provided by the Location field, as in the status codes
301
(Moved Permanently),302
(Found), and307
(Temporary Redirect).Redirection that offers a choice of matching resources, each capable of representing the original request target, as in the
300
(Multiple Choices) status code.Redirection to a different resource, identified by the Location field, that can represent an indirect response to the request, as in the
303
(See Other) status code.Redirection to a previously cached result, as in the
304
(Not Modified) status code.
正确的取决于您的需要。然而,这些是最常见的:
The
301
(Moved Permanently) status code indicates that the target resource has been assigned a new permanent URI and any future references to this resource ought to use one of the enclosed URIs. [...]
The
303
(See Other) status code indicates that the server is redirecting the user agent to a different resource, as indicated by a URI in the Location header field, which is intended to provide an indirect response to the original request. [...]
The
307
(Temporary Redirect) status code indicates that the target resource resides temporarily under a different URI and the user agent MUST NOT change the request method if it performs an automatic redirection to that URI. [...]
在 JAX-RS 中执行重定向
根据您在问题中发布的代码,我相信您使用的是 JAX-RS应用程序接口(interface)。如果是这样,您可以按如下方式执行重定向:
URI uri = ...
return Response.status(Status.MOVED_PERMANENTLY).location(uri).build();
- 303 See Other (又名 POST/重定向/GET):
URI uri = ...
return Response.seeOther(uri).build();
URI uri = ...
return Response.temporaryRedirect(uri).build();
有关更多详细信息,Response
类文档可能会有用。
在使用 JAX-RS 时可能有用的其他细节
您还可以注入(inject) UriInfo
在您的 REST 端点中:
@Context
UriInfo uriInfo;
并得到一些有用的信息,比如base URI和 absolute path of the request .这在构建用于重定向的 URI 时很有用。
带有重定向的资源方法如下:
@Path("/foo")
public class MyEndpoint {
@Context
private UriInfo uriInfo;
@POST
@Produces(MediaType.APPLICATION_JSON)
public Response myMethod() {
URI uri = uriInfo.getBaseUriBuilder().path("bar").build();
return Response.temporaryRedirect(uri).build();
}
}
关于java - 使用 REST 重定向 URL 的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36638150/