Jax-RS Response.created(location) 用于带有路径参数的路由
Jax-RS Response.created(location) for routes with path parameters
我有一个 REST 路由来创建使用路径参数的资源。
这里给出的答案:
展示了如何使用 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 中的路径参数,这不会导致正确的资源。
POST:http://localhost/api/resource/{type} 路径参数类型 = "system"
will return http://localhost/api/resource/system/123(123是生成的id)
而正确的 URI 应该是
http://localhost/api/resource/123
那么,我怎样才能获得 return 的正确资源位置?
是的,按照 link 中的方式进行操作,您假设父子关系,您将在其中发布到集合端点并创建子单一资源。对于您的用例,情况并非如此。使它起作用的一种方法是只使用 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
我有一个 REST 路由来创建使用路径参数的资源。
这里给出的答案: 展示了如何使用 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 中的路径参数,这不会导致正确的资源。
POST:http://localhost/api/resource/{type} 路径参数类型 = "system"
will return http://localhost/api/resource/system/123(123是生成的id) 而正确的 URI 应该是 http://localhost/api/resource/123
那么,我怎样才能获得 return 的正确资源位置?
是的,按照 link 中的方式进行操作,您假设父子关系,您将在其中发布到集合端点并创建子单一资源。对于您的用例,情况并非如此。使它起作用的一种方法是只使用 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