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

21

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

我发现了这行示例代码,但是它是用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。

谢谢你的帮助。

2个回答

54
我认为你的意思是要做类似于Response.created(createdURI).build()这样的操作。这将创建一个带有 createdUri 作为位置标头值的201 Created状态的响应。通常情况下,这是使用POST请求完成的。在客户端上,您可以调用Response.getLocation()来获取新URI。从Response API中了解更多信息。 请记住关于您指定给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();

如果在资源创建中使用路径参数,则此UriInfo解决方案将无法正常工作。有关如何处理这种情况的建议?UriInfo似乎没有提供直接获取完整路径但不包含任何pathparams的简单方法。 - Senshi
@Senshi 不确定你的意思。你能发另一个带例子的问题吗?我确定有解决方案,但我不太确定问题是什么。 - Paul Samsotha
当然可以。我会感激您的意见 :) https://stackoverflow.com/q/52773898/2436002 - Senshi
嗨,这个UriInfo类与jax/rs一起工作,是否有任何可以为Spring提供相同功能的东西?我已经搜索过了,现在我正在使用ServletContext创建,但不如前者好。 - ThinkTank

-1
 @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();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接