Java Reference
In-Depth Information
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 Conneg with JAXB
XML and JSON. If you leverage JAX-RS integration with conneg, you can implement one
Java method that can service both formats. This can save you from writing a whole lot of
boilerplate code:
@Path
(
"/service"
)
public
public class
class
MyService
MyService
{
@GET
@Produces
({
"application/xml"
,
"application/json"
})
public
public
Customer
getCustomer
(
@PathParam
(
"id"
)
int
int
id
) {...}
}
In this example, our
getCustomer()
method produces either XML or JSON, as denoted by
the
@Produces
annotation applied to it. The returned object is an instance of a Java class,
Customer
, which is annotated with JAXB annotations. Since most JAX-RS implementations
support using JAXB to convert to XML or JSON, the information contained within our
Ac-
cept
header can pick which
MessageBodyWriter
to use to marshal the returned Java object.
Complex Negotiation
Sometimes simple matching of the
Accept
header with a JAX-RS method's
@Produces
an-
notation is not enough. Different JAX-RS methods that service the same URI may be able to
deal with different sets of media types, languages, and encodings. Unfortunately, JAX-RS
does not have the notion of either an
@ProduceLanguages
or
@ProduceEncodings
annota-
tion. Instead, you must code this yourself by looking at header values directly or by using the
JAX-RS API for managing complex conneg. Let's look at both.