You are previewing RESTful Java with JAX-RS.

RESTful Java with JAX-RS

Cover of RESTful Java with JAX-RS by Bill Burke Published by O'Reilly Media, Inc.
O'Reilly logo

@PathParam

We looked at @javax.ws.rs.PathParam a little bit in Chapters 3 and 4. @PathParam allows you to inject the value of named URI path parameters that were defined in @Path expressions. Let’s revisit the CustomerResource example that we defined in Chapter 2 and implemented in Chapter 3:

@Path("/customers")
public class CustomerResource {
   ...

   @Path("{id}")
   @GET
   @Produces("application/xml")
   public StreamingOutput getCustomer(@PathParam("id") int id) {
     ...
   }
}

In this example, we want to route HTTP GET requests to the relative URI pattern /customers/{id}. Our getCustomer() method extracts a Customer ID from the URI using @PathParam. The value of the @PathParam annotation, "id", matches the path parameter, {id}, that we defined in the @Path expression of getCustomer().

While {id} represents a string segment in the request’s URI, JAX-RS automatically converts the value to an int before it invokes the getCustomer() method. If the URI path parameter cannot be converted to an integer, the request is considered a client error and the client will receive a 404, “Not Found” response from the server.

More Than One Path Parameter

You can reference more than one URI path parameter in your Java methods. For instance, let’s say we are using first and last name to identify a customer in our CustomerResource:

@Path("/customers")
public class CustomerResource {
   ...

   @Path("{first}-{last}")
   @GET
   @Produces("application/xml")
   public StreamingOutput getCustomer(@PathParam("first") String firstName,
                                      @PathParam("last") ...

The best content for your career. Discover unlimited learning on demand for around $1/day.