【问题标题】:Jax-RS Response.created(location) for routes with path parameters带有路径参数的路由的 Jax-RS Response.created(location)
【发布时间】:2018-10-12 06:53:31
【问题描述】:

我有一个 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

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

【问题讨论】:

    标签: java jax-rs


    【解决方案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

    【讨论】:

    • 这是我问题的正确答案。但由于我的实际类包含多个方法,我无法使用 fromResource。但它让我走上了正轨,并且 fromMethod(Resource.class, "methodname") 效果很好!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-14
    • 2017-09-02
    • 2012-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多