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

JAX-RS and Conneg

The JAX-RS specification has a few facilities that help you manage conneg. It does method dispatching based on Accept header values. It allows you to view this content information directly. It also has complex negotiation APIs that allow you to deal with multiple decision points. Let’s look into each of these.

Method Dispatching

In previous chapters, we saw how the @Produces annotation denotes which media type a JAX-RS method should respond with. JAX-RS also uses this information to dispatch requests to the appropriate Java method. It matches the preferred media types listed in the Accept header of the incoming request to the metadata specified in @Produces annotations. Let’s look at a simple example:

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

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

   @GET
   @Path("{id}")
   @Produces("text/plain")
   public String getCustomerText(@PathParam("id") int id) {...}

   @GET
   @Path("{id}")
   @Produces("application/json")
   public Customer getCustomerJson(@PathParam("id") int id) {...}
}

Here, we have three methods that all service the same URI but produce different data formats. JAX-RS can pick one of these methods based on what is in the Accept header. For example, let’s say a client made this request:

GET http://example.com/customers/1
Accept: application/json;q=1.0, application/xml;q=0.5

The JAX-RS provider would dispatch this request to the getCustomerJson() method.

Leveraging ...

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