O'Reilly logo

RESTful Java with JAX-RS by Bill Burke

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

@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") ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required