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 
           The @Path annotation allows the inclusion of path elements which could be dynamically mapped at the time of invocation. Such elements are encoded in {}. The page from the JSR-311 spec describes how path matching is done when such path elements are used in a resource's path definition.
  • Another new annotation - @PathParam

             The @PathParam is another annotation from JAX-RS. This takes care of mapping a path identifier to a method parameter.

Comments:

Excellent! That's just the info I needed :-) Nice and succinct.

Much appreciated, Naresh.

-Todd

Posted by Todd Fiala on September 10, 2009 at 08:18 AM PDT #

Post a Comment:
  • HTML Syntax: NOT allowed
About

Naresh worked at Sun Microsystems for two years. During these two years he had worked on the Project Metro and Project Jersey.

Search

Categories
Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today