When defining web service resource URLs, you may find yourself in the situation in which you want path parameters to be viable in any order. For example, shouldn't these two URL's both be accaptable, and point to the same resource?
.../person/firstname/geoff/lastname/hendrey
.../person/lastname/hendrey/firstname/geoff
I've found that the best way to do this is to creat a single resource class, in this case Person, and to define subresource locator methods for "firstname/{firstname}" and "lastname/{lastname}". The trick is to return "this" in your subresource locator method, which affectively turns the subresource locators into a means to setting instance fields on the Person instance.
So when we look in the "PersonResource" class, our subresource locator method for 'firstname' is:
@Path("/person")
public class PersonResource{
private String firstname;
private String lastname;
@Path("firstname/{firstname}") //subresource
public Person getSubResource(@PathParam("firstname") String fname){
this.firstname=fname; //set instance field on this resource
return this;
}
@Path("lastname/{lastname}") //subresource
public Person getSubResource(@PathParam("lastname") String lname){
this.lastname=lname; //set instance field on this resource
return this;
}
}
The locator method for lastname follows the same patter. And that's all there is to it! I have not found this pattern covered or described in any of the docs for Jersey, but I have found it indespensible.
Sunday, November 22, 2009
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment