2015-05-25 88 views
3

我有一个泽西岛2.x端点,用户可以POST以更新父资源上的特定属性。成功时,我想返回303状态并在Location标题中指定父资源的路径。查找泽西父路径

例如。如果用户发布到:

http://example.com/api/v1/resource/field 

然后设置位置标头在应对:

http://example.com/api/v1/resource 

好像有应与UriInfo/UriBuilder这样做一个简单的方法,但我不知道如何做到这一点,而不需要对以后可能会中断的事情进行硬编码。

回答

3

UriInfo.getBaseUriBuilder()获取基本URI(假设为http://example.com/api),然后将XxxResource路径附加到builder.path(XxxResource.class)

然后从内置的URI返回Response.seeOther(uri).build();。完整示例:

@Path("/v1/resource") 
public class Resource { 

    @GET 
    public Response getResource() { 
     return Response.ok("Hello Redirects!").build(); 
    } 

    @POST 
    @Path("/field") 
    public Response getResource(@Context UriInfo uriInfo) { 
     UriBuilder uriBuilder = uriInfo.getBaseUriBuilder(); 
     uriBuilder.path(Resource.class); 
     URI resourceBaseUri = uriBuilder.build(); 
     return Response.seeOther(resourceBaseUri).build(); 
    } 
} 
+0

谢谢!我试图使用路径(Resource.class,“methodName”)来获取资源上特定方法的路径,但我想只会返回相对于包含资源的方法。加入路径(Resource.class)让我得到了我需要的东西。 –