Making the URI dynamic
"I have a resource which does something. I want the same thing to be done for another use case. The only thing that differs is some part of the identifier. Do I have to create one more resource for this requirement? Just wondering if there were a way where I could make the identifier dynamic and use the same resource for all such use cases?" - these are some of the common questions that most of the people working on REST get into, at one or the other time.
Is there really a way, where the URI could be made dynamic??? And the answer is YES.
JAX-RS provides a way of making the URI of the resource dynamic. I know, the next question is HOW???
Lets see how this could be done by modifying the same HelloWorldWebApp developed in one of the previous entries:
- Modify the @Path annotation given above the HelloResource class as follows:
@Path("hello/{name}")
public class HelloResource {
- Overwrite the sayHello method with the following:
@GET
@Produces("text/plain")
public String sayHello(@PathParam ("name") String name) {
return "Hello " + name + "!";
}
- Redeploy the application. Enter the URL http://localhost:8080/HelloWorldWebapp/resources/hello/Rama in a web browser, and you will see the response Hello Rama! . Change the Rama in the URL to Raja and you will see Hello Raja! .
So how is it happening?
We see two new things here:
- A different way of passing path information to the @Path annotation
- Another new annotation - @PathParam
The @PathParam is another annotation from JAX-RS. This takes care of mapping a path identifier to a method parameter.
Excellent! That's just the info I needed :-) Nice and succinct.
Much appreciated, Naresh.
-Todd
Posted by Todd Fiala on September 10, 2009 at 03:18 PM PDT #