Search code examples
javajerseyjax-rs

Find Jersey Parent Path


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

eg. if the user POSTed to:

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

then set the location header in the response to:

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

It seems like there should be a straightforward way to do this with UriInfo/UriBuilder, but I'm at a loss as to how to do it without hard-coding something that's likely to break later on.


Solution

  • Get the base URI (which assuming is http://example.com/api) from UriInfo.getBaseUriBuilder(), then append the XxxResource path with builder.path(XxxResource.class).

    Then from the built 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) {
            URI resourceBaseUri = uriInfo.getBaseUriBuilder()
                .path(Resource.class)
                .build();
            return Response.seeOther(resourceBaseUri).build();
        }
    }