在JAX-RS中使用Location头创建响应

men*_*h84 11 c# java jax-rs

我在NetBeans中使用来自实体的RESTful模板自动生成类,具有CRUD函数(使用POST,GET,PUT,DELETE注释).我有一个create方法的问题,在从前端插入实体后,我想创建更新响应,以便我的视图将自动(或异步,如果这是正确的术语)反映添加的实体.

我遇到了这个(示例)代码行,但用C#编写(我对此一无所知):

HttpContext.Current.Response.AddHeader("Location", "api/tasks" +value.Id);
Run Code Online (Sandbox Code Playgroud)

在Java中使用JAX-RS,无论如何都可以像在C#中一样获取当前的HttpContext并操纵头文件?

我最接近的是

Response.ok(entity).header("Location", "api/tasks" + value.Id);
Run Code Online (Sandbox Code Playgroud)

这个肯定是行不通的.在构建Response之前,我似乎需要获取当前的HttpContext.

谢谢你的帮助.

Pau*_*tha 38

我认为你的意思是做类似的事情Response.created(createdURI).build().这将创建一个具有201 Created状态的响应,其中createdUri包含位置标头值.通常这是通过POST完成的.在客户端,您可以调用Response.getLocation()哪个将返回新的URI.

来自Response API

请记住location您为created方法指定的内容:

新资源的URI.如果提供了相对URI,则通过相对于请求URI解析它,将其转换为绝对URI.

如果您不想依赖静态资源路径,则可以从UriInfo类中获取当前的uri路径.你可以做点什么

@Path("/customers")
public class CustomerResource {
    @POST
    @Consumes(MediaType.APPLICATION_XML)
    public Response createCustomer(Customer customer, @Context UriInfo uriInfo) {
        int customerId = // create customer and get the resource id
        UriBuilder builder = uriInfo.getAbsolutePathBuilder();
        builder.path(Integer.toString(customerId));
        return Response.created(builder.build()).build();
    }
}
Run Code Online (Sandbox Code Playgroud)

这将创建位置.../customers/1(或其他任何位置customerId),并将其作为响应头发送

请注意,如果要将实体与响应一起发送,则只需将其附加entity(Object)到方法链即可Response.ReponseBuilder