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

Chapter 18. Examples for Chapter 5

Chapter 5 showed you how to use JAX-RS annotations to inject specific information about an HTTP request into your Java methods and fields. This chapter implements most of the injection scenarios introduced in Chapter 5 so that you can see these things in action.

Example ex05_1: Injecting URI Information

This example illustrates the injection annotations that are focused around pulling in information from the incoming request URI. Specifically, it shows how to use @PathParam, @MatrixParam, and @QueryParam. Parallel examples are also shown using javax.ws.rs.core.UriInfo to obtain the same data.

The Server Code

The first thing you should look at on the server side is CarResource. This class pulls the various examples in Chapter 5 together to illustrate using @MatrixParam and @PathParam with the javax.ws.rs.core.PathSegment class:

src/main/java/com/restfully/shop/services/CarResource.java

@Path("/cars")
public class CarResource
{
   public static enum Color
   {
      red,
      white,
      blue,
      black
   }

   @GET
   @Path("/matrix/{make}/{model}/{year}")
   @Produces("text/plain")
   public String getFromMatrixParam(
                             @PathParam("make") String make,
                             @PathParam("model") PathSegment car,
                             @MatrixParam("color") Color color,
                             @PathParam("year") String year)
   {
      return "A " + color + " " + year + " "
                  + make + " " + car.getPath();
   }

The getFromMatrixParam() method uses the @MatrixParam annotation to inject the matrix parameter color. An example of a URI it could process is /cars/matrix/mercedes/e55;color=black/2006 ...

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