2014-09-29 34 views
10

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

我碰到这个(例子)的代码行,但写在C#(其中我知道什么):

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

在Java中使用JAX-RS,反正是有得到当前的HttpContext刚像在C#和操纵头?

我来最接近的是

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

,这一次肯定是行不通的。看起来我需要在构建响应之前获取当前的HttpContext。

感谢您的帮助。

回答

30

我想你的意思是做一些像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(); 
    } 
} 

这将创建位置.../customers/1(或任何customerId是),如果你想与响应一起发送实体发送的响应头

注,你可以附上entity(Object)到的Response.ReponseBuilder

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

方法链请描述添加到你的答案和代码 – ztadic91 2017-11-28 01:07:56