我有一个 REST 路由来创建使用路径参数的资源。
这里给出的答案: https://stackoverflow.com/a/26094619/2436002 展示如何使用 UriInfo 上下文轻松地为响应创建正确的位置 header 。
@Path("/resource/{type}")
public class Resource {
@POST
public Response createResource(@PathParam("type") String type, @Context UriInfo uriInfo)
{
UUID createdUUID = client.createResource(type);
UriBuilder builder = uriInfo.getAbsolutePathBuilder();
builder.path(createdUUID.toString());
return Response.created(builder.build()).build();
}
}
但是,这包括接收到的 URI 中的路径参数,这不会导致正确的资源。
帖子:http://localhost/api/resource/ {type},路径参数类型=“系统”
将返回http://localhost/api/resource/system/123 (123是生成的id) 而正确的 URI 是 http://localhost/api/resource/123
那么,如何才能返回正确的资源位置?
最佳答案
是的,按照链接中的方式执行此操作,您假设存在父子关系,您将发布到集合端点并创建子单个资源。对于您的用例,情况并非如此。使其工作的一种方法是仅使用 UriBuilder.fromResource()
。然后只需调用 resolveTemplate()
来输入 "type"
的值即可。
URI createdUri = UriBuilder.fromResource(Resource.class)
.resolveTemplate("type", createdUUID.toString()).build();
return Response.created(uri).build();
这将为您提供http://localhost/api/resource/123
关于java - Jax-RS Response.created(location) 用于带有路径参数的路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52773898/