Java Reference
In-Depth Information
textResolver() on each individual resolver in the list. If it returns a JAXBContext instance,
it returns that to the original caller; otherwise, it tries the next resolver in this list.
MessageBodyReader
Now that we have written a MessageBodyWriter to convert a Java object into XML and out-
put it as the HTTP response body, let's write an unmarshaller that knows how to convert
HTTP XML request bodies back into a Java object. To do this, we need to use the
javax.ws.rs.ext.MessageBodyReader interface:
public
public interface
interface MessageBodyReader
MessageBodyReader < T > {
boolean
boolean isReadable ( Class <?> type , Type genericType ,
Annotation annotations [], MediaType mediaType );
T readFrom ( Class < T > type , Type genericType ,
Annotation annotations [], MediaType mediaType ,
MultivaluedMap < String , String > httpHeaders ,
InputStream entityStream )
throws
throws IOException , WebApplicationException ;
}
The MessageBodyReader interface has only two methods. The isReadable() method is
called by the JAX-RS runtime when it is trying to find a MessageBodyReader to unmarshal
the message body of an HTTP request. The readFrom() method is responsible for creating a
Java object from the HTTP request body.
Implementing a MessageBodyReader is very similar to writing a MessageBodyWriter . Let's
look at how we would implement one:
@Provider
@Consumes ( "application/xml" )
public
public class
class JAXBUnmarshaller
JAXBUnmarshaller implements
implements MessageBodyReader {
public
public boolean
boolean isReadable ( Class <?> type , Type genericType ,
Annotation annotations [], MediaType mediaType ) {
return
return type . isAnnotationPresent ( XmlRootElement . class );
}
Our JAXBUnmarshaller class is annotated with @Provider and @Consumes . The latter an-
notation tells the JAX-RS runtime which media types it can handle. The matching rules for
finding a MessageBodyReader are the same as the rules for matching MessageBodyWriter .
Search WWH ::




Custom Search