The JAX-RS framework uses entity provider components for the marshaling and unmarshaling of the message body content (entity) present in the response and request objects, respectively. It is the entity provider component that maps an entity with the associated Java types.
The following table lists the default entity mappings provided by the JAX-RS runtime via a set of built-in entity providers. When you use one of the internet media types present in the following table to represent the request or response entity body, the framework takes care of the conversion and reconversion of the entity body to the associated Java type:
Data types |
Internet media type |
byte[] |
*/* |
java.lang.String |
*/* |
java.io.Reader |
*/* |
java.io.File |
*/* |
javax.activation.DataSource |
*/* |
javax.ws.rs.core.StreamingOutput |
*/* |
All primitive types |
text/plain |
java.lang.Boolean |
text/plain |
java.lang.Character |
text/plain |
java.lang.Number |
text/plain |
javax.xml.transform.Source |
text/xml, application/xml, and application/*+xml |
javax.xml.bind.JAXBElement |
text/xml, application/xml, and application/*+xml |
Application supplied JAXB annotated objects (types annotated with @XmlRootElement or @XmlType) |
text/xml, application/xml, and application/*+xml |
javax.ws.rs.core.MultivaluedMap<String, String> |
application/x-www-form-urlencoded |
What if you want to build your own media type for representing the message content? Or what if you want to customize the marshaling and unmarshaling process for specific media types?
JAX-RS has a solution for both these use cases. The JAX-RS extension API allows you to handle the request or response message bodies via custom entity providers. You can have custom entity providers configured for an application for serializing the Java type into the appropriate media type. They can also be used for deserializing the message body content present in a request to the appropriate Java types. In this section, we will learn how to use the JAX-RS provider APIs for building custom message handlers.
The JAX-RS extension API offers the following two contracts (interfaces) for managing the marshaling and unmarshaling of the entity body present in the request and response messages:
- javax.ws.rs.ext.MessageBodyWriter<T>: This interface provides the contract for the conversion of a Java type to the output stream. The class that implements this interface converts the message payload represented in Java into the one on the internet media type representation format that is sent over the wire to the client.
- javax.ws.rs.ext.MessageBodyReader<T>: This interface provides the contract for the conversion of the input stream to a Java type. The provider class that implements this interface reads the message body representation from the input stream and converts the incoming message body into an appropriate Java type.