Create Response with Location header in JAX-RS

I think you mean to do something like Response.created(createdURI).build(). This will create a response with a 201 Created status, with the createdUri being the location header value. Normally this is done with POSTs. On the client side, you can call Response.getLocation() which will return the new URI.

From the Response API

  • public static Response.ResponseBuilder created(URI location) - Create a new ResponseBuilder for a created resource, set the location header using the supplied value.

  • public abstract URI getLocation() - returns the location URI, otherwise null if not present.

Keep in mind about the location you specify to the created method:

the URI of the new resource. If a relative URI is supplied it will be converted into an absolute URI by resolving it relative to the request URI.

If you don't want to rely on static resource paths, you could get the current uri path from the UriInfo class. You could do something like

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

This would create the location .../customers/1 (or whatever the customerId is), and send it as the response header

Note if you want to send the entity along with the response, you can just attach the entity(Object) to the method chain of the Response.ReponseBuilder

return Response.created(uriBuilder.build()).entity(newCustomer).build();

Tags:

C#

Java

Jax Rs