Java Reference
In-Depth Information
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 Cus-
tomerResource.getCustomer() method:
@Path ( "/customers" )
public class
class CustomerResource
CustomerResource {
@Path ( "{id}" )
@Produces ({ "application/xml" , "application/json" })
public Customer getCustomer ( @PathParam ( "id" ) int
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 ap-
propriate media type of the response for getCustomer() . If the Accept header is applica-
tion/xml , XML will be produced. If the Accept header is JSON, the Customer object will
be outputted as JSON.
The second concept being highlighted here is that you can use the @Produces annotation to
dispatch to different Java methods. To illustrate this, we've added the getCustomer-
String() method, which processes the same URL as getCustomer() but for a different me-
dia type:
Search WWH ::

Custom Search