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

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

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

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

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

我最接近的是

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

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

谢谢你的帮助。

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

来自Response API

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

  • 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 builder = uriInfo.getAbsolutePathBuilder(); builder.path(Integer.toString(customerId)); return Response.created(builder.build()).build(); } } 

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

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

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