O'Reilly logo

RESTful Java with JAX-RS 2.0, 2nd Edition 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

Chapter 23. Examples for Chapter 9

In Chapter 9, 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 ex09_1: Conneg with JAX-RS

This example is a slight modification from ex06_1 and shows two different concepts. First, the same JAX-RS resource method can process two different media types. Chapter 9 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 ex09_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, the ...

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