1

我有一个 REST 路由来创建使用路径参数的资源。

此处给出的答案: https : //stackoverflow.com/a/26094619/2436002 展示了如何使用 UriInfo 上下文轻松地为响应创建适当的位置标头。

@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 中的路径参数,这不会导致正确的资源。

POST: http://localhost/api/resource/ {type} 与 pathparam type = "system"

将返回http://localhost/api/resource/system/123(123 是生成的 id),而正确的 URI 将是 http://localhost/api/resource/123

那么,我怎样才能让正确的资源位置返回呢?

4

1 回答 1

1

是的,按照链接中的方式进行操作,您假设父子关系,您将在其中发布到集合端点并创建子单个资源。对于您的用例,情况并非如此。使其工作的一种方法是仅使用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

于 2018-10-12T16:11:21.110 回答