Chapter 21. Examples for Chapter 8

In Chapter 8, you learned that clients can use HTTP Content Negotiation to request different data formats from the same URL using the Accept header. You also learned that JAX-RS takes the Accept header into account when deciding how to dispatch an HTTP request to a Java method. In this chapter, you’ll see two different examples that show how JAX-RS and HTTP conneg can work together.

Example ex08_1: Conneg with JAX-RS

This example is a slight modification from ex06_1 and shows two different concepts. The first is that the same JAX-RS resource method can process two different media types. Chapter 8 gives the example of a method that returns a JAXB annotated class instance that can be returned as either JSON or XML. We’ve implemented this in ex08_1 by slightly changing the CustomerResource.getCustomer() method:

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

@Path("/customers")
public class CustomerResource {
...
   @GET
   @Path("{id}")
   @Produces({"application/xml", "application/json"})
   public Customer getCustomer(@PathParam("id") int id)
   {
      ...
   }

The JAXB provider that comes with RESTEasy can convert JAXB objects to JSON or XML. In this example, we have added the media type application/json to getCustomer()’s @Produces annotation. The JAX-RS runtime will process the Accept header and pick the appropriate media type of the response for getCustomer(). If the Accept header is application/xml, XML will be produced. If the Accept header is JSON, ...

Get RESTful Java with JAX-RS now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.