Sunday, November 22, 2009

Order-invariant Path Parameters with JSR-311 JAX-RS and Jersey

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?


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:

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.

No comments:

Post a Comment