users@jersey.java.net

Re: [Jersey] Inheriting _at_Path Question

From: Marc Hadley <Marc.Hadley_at_Sun.COM>
Date: Thu, 05 Mar 2009 18:54:04 -0500

On Mar 5, 2009, at 5:46 PM, Rabick, Mark A (MS) wrote:
> Is there a way to inherit pathing from superclasses of a resource?
>
> Ie.
>
> <Base Class>
> @Path("/v1")
> public class V1BaseResource {
> @Context
> protected UriInfo uriInfo;
> }
> </Base Class>
>
> <Sub Class>
> @Path("/node")
> public class V1NodeResource extends V1BaseResource {
>
> @GET @Path("/{key}")
> @Produces(MediaType.APPLICATION_XML)
> public Node getNodeByKey( @PathParam("key") String key ) {
> return NodeDB.getNodeByKey(key);
> }
> }
> </Sub Class>
>
> Where the URI would be like:
>
> http://localhost:7001/rest/root/v1/node/11111
>
> That would allow all methods in the V1NodeResource sub-class to have
> the shared URI root of "v1".
>
> Is such a thing possible?
>

You need to use sub resource locators rather than inheritance for
that, e.g.

@Path("v1")
public class V1BaseResource {

   @Context protected UriInfo uriInfo;

   @Path("node")
   public V1NodeResource getNode() {
     return new V1NodeResource(uriInfo);
   }
}

public class V1NodeResource {
     @GET @Path("/{key}")
     @Produces(MediaType.APPLICATION_XML)
     public Node getNodeByKey( @PathParam("key") String key ) {
         return NodeDB.getNodeByKey(key);
     }
}

Now when you GET http://localhost:7001/rest/root/v1/node/11111, Jersey
will match the request to V1BaseResource for the initial "v1" path
segment and then call the getNodeMethod since it matches the next
"node" path segment. The object returned by getNodeMethod will then be
treated as a resource class for the remaining part of the path "11111"
so it will call getNodeByKey("11111").

Note that there's no @Path on the V1NodeResource class, it can only be
reached through a matching sub resource locator (V1BaseResource.
getNode).

HTH,
Marc.