users@jersey.java.net

Re: One Resource class for two URLs

From: Martin Probst <mail_at_martin-probst.com>
Date: Tue, 22 Apr 2008 11:29:25 +0200

Hi,

> If you could have "/books" and "/books/book/{id}" it may make things
> easier for you.

This is what I previously did, but it didn't quite feel right.

> @Path("books")
> class Books {
> @Path("book/{id}") getBook(...) { ... }
> }
>
> It adds a bit of redundancy to the URI space but i still think it is
> "cool" enough (in terms of Cool URIs).

I think I found a solution that is about 17% more cool ;-)

I'm now supplying my own "HibernateComponentProvider" into the
webapplication. I'm not sure if this qualifies as a clever solution or
an ugly hack (feedback please!), but it works like this:

I have @Path("books") class Books { ... } and @Path("book/{id}") class
Book { ... }. Book has a constructor that takes a single long "id"
@PathParam (not sure the annotation is necessary). Thus, the
HibnernateComponentProvider#newInstance method is called with
parameters, and I use those to read the resource instance from the
persistence provider.

I couldn't quite make out by what means Jersey picks the constructor
to use for the query, is there any documentation on this? I fear that
my solution simply exploits the undocumented current behaviour and
might break later on. Maybe this could be a bit formalized, so people
can supply Factory methods for their Resources easily (which is
essentially what I'm doing).

I still need to inject classes in the persistence layer for my methods
that search resources (e.g. by title) using direct Hibernate queries,
so classes might get injected by Jersey twice, but I think this
shouldn't be a problem.

Anyways, I can now have persistent classes that are directly available
as Root resources, no navigation through a collection class required,
thus I can have:
/books -> Books, "collection instance", constructed directly
/book/12 -> single Book instance, loaded from Hibernate

It's pretty cool that this is possible with Jersey's implementation as
is, no changes necessary, even though it probably is an unexpected use
case. Great work!

Regards,
Martin