在JAX-RS中创建带有Location标头的响应

本文关键字:响应 Location JAX-RS 创建 | 更新日期: 2023-09-27 18:24:50

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

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

HttpContext.Current.Response.AddHeader("Location", "api/tasks" +value.Id);

在Java中使用JAX-RS,是否可以像在C#中一样获得当前的HttpContext并操作头?

我最接近的是

Response.ok(entity).header("Location", "api/tasks" + value.Id);

这个肯定不起作用。在构建响应之前,我似乎需要获取当前的HttpContext。

谢谢你的帮助。

在JAX-RS中创建带有Location标头的响应

我想你的意思是做一些类似Response.created(createdURI).build()的事情。这将创建一个状态为201 Created的响应,其中createdUri是位置标头值。通常情况下,这是通过海报完成的。在客户端,您可以调用Response.getLocation(),它将返回新的URI。

来自响应API

  • public static Response.ResponseBuilder created(URI location)-为创建的资源创建一个新的ResponseBuilder,使用提供的值设置位置标头。

  • public abstract URI getLocation()-返回位置URI,否则为null(如果不存在)。

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

新资源的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 uriBuilder = uriInfo.getAbsolutePathBuilder();
        uriBuilder.path(Integer.toString(customerId));
        return Response.created(uriBuilder.build()).build();
    }
}

这将创建位置.../customers/1(或customerId是什么),并将其作为响应标头发送

注意,如果您想将实体与响应一起发送,您可以将entity(Object)附加到Response.ReponseBuilder 的方法链上

return Response.created(uriBuilder.build()).entity(newCustomer).build();
 @POST
public Response addMessage(Message message, @Context UriInfo uriInfo) throws URISyntaxException
{
    System.out.println(uriInfo.getAbsolutePath());
    Message newmessage = messageService.addMessage(message);
    String newid = String.valueOf(newmessage.getId()); //To get the id
    URI uri = uriInfo.getAbsolutePathBuilder().path(newid).build();
    return Response.created(uri).entity(newmessage).build();
}