On May 11, 2008, at 11:13 PM, Bruno Luiz Pereira da Silva wrote:
> Hi guys, I'd like to ask you something related to the Location
> header set when we create a new resource.
>
> Resource.created(uri) does something that I think is kind of rigid.
> If I pass an absolute URI, it respects it, just fine. I'd like to
> discuss what it does when we send a relative URI.
>
> When I use a relative URI, Jersey converts it to an absolute URI
> relative to the resource's root URI. In some cases this is just
> fine, but sometimes I'd like to set it differently.
>
The current handling of relative URIs in a created response is based
on the container+item pattern where the new resource is relative to
the current one. We need a well-defined base URI to resolve any
relative URIs against and really it was a choice between the URI of
the current resource or the base URI of the application - the former
seemed better since it optimizes a common pattern.
> For example, let's take an example of eBay services, where the
> collection of products belonging to an user is located at /user/{id}/
> products. To add a new product for this user, we could POST the
> product at /user/{id}/products. However, I'd like to access this
> product at /products/{id}.
>
> If I have an User resource mapped to /user, and a method mapped with
> @Path("{userId}/products"), the only way I can return a Location
> header pointing at /products/{id} is using an absolute URI.
>
> I'd like to be able to set the Location header to /products/{id}
> using a relative URI, even inside a different path (/user in this
> case). Do you think it makes sense or am I willing to do something
> inadequate?
>
I don't think what you want to do is really that difficult:
@Context UriInfo ui;
URI absoluteLocation = UriInfo.getBaseUriBuilder().path("products/
{id}").build(myProductId);
Compare the above to the case if we resolved against the application
base URI instead:
URI relativeLocation = UriBuilder.fromPath("products/
{id}").build(myProductId);
The main problem with switching to using the application base URI is
that everyone would then have to include the path to the container
resource when using the container+item pattern.
Marc.
---
Marc Hadley <marc.hadley at sun.com>
CTO Office, Sun Microsystems.