Java Reference
In-Depth Information
Creating a Single Path for Variable Resources of the
Same Type
Problem
You want to create a class that can respond for many instances of the same type. That is, you
don't want to have a separate individual class for each individual resource, as this would be a
maintenance nightmare. You want, for example, to have representations for /products/1 and
/products/2 map to the same class.
Solution
Use a template in the @Path element on your class, defining the variable part in curly braces.
Then use the @PathParam annotation on your method parameters.
Discussion
In a RESTful URL, such as that for the Google Finance Portfolio application in Application:
Using SSL, Atom Publishing, and the Google Finance REST API , you see a drill-down struc-
ture that moves from general categories to specific instances. In the case of the Google Fin-
ance app, you can access a specific portfolio using a URL that includes the ID for the portfolio
you want to get data for, like this: /finance/feeds/default/portfolios/3 . Here, 3 is the
ID of the specific portfolio you want to view. You need to be able to create URIs like this in
JAX-RS, without having to create a separate class for every single resource you might want
to return a representation of. Doing so would be a maintenance nightmare, and isn't how good
applications are designed.
For this reason, the JAX-RS API provides a way to handle just this situation, called URItem-
plates. A root resource is assigned a specific URI root path using the @Path annotation at the
class level. This path follows the context path of the application, and allows you to assign dy-
namic resources using what's called a pathparameter. A path parameter is defined in curly
braces inside the value of the path itself. You then match that parameter value to a method
parameter using the annotation @PathParam . This sounds much more complicated than it is.
An example will make it clear.
In Example 8-8 , you define a method that will respond to GET requests for products, accept a
parameter for a product ID, and return the appropriate representation.
Example8-8.Using a PathParameter to get specific products in a RESTful URI
Search WWH ::




Custom Search