Find the Parenting Path Jersey

I have a Jersey 2.x endpoint where a user can POST to update a specific property on a parent resource. On success, I would like to return a 303 status and provide the path to the parent resource in the header Location

.

eg. if user is POSTed:

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

      

then set the location header in the answer to:

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

      

It seems like there should be an easy way to do this with UriInfo

/ UriBuilder

, but I don't understand how to do this without hardcoding that might break later.

+3


source to share


1 answer


Get the base URI (which counts http://example.com/api

) from UriInfo.getBaseUriBuilder()

, then add the path XxxResource

to builder.path(XxxResource.class)

.

Then from inline, URI

return Response.seeOther(uri).build();

. Complete example:



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

      

+3


source







All Articles