You are previewing RESTful Java with JAX-RS.

RESTful Java with JAX-RS

Cover of RESTful Java with JAX-RS by Bill Burke Published by O'Reilly Media, Inc.

Example ex06_2: Creating a Content Handler

For this example, we’re going to create something entirely new. The Chapter 6 example of a content handler is a reimplementation of JAXB support. It is suitable for that chapter because it illustrates both the writing of a MessageBodyReader and MessageBodyWriter and demonstrates how the ContextResolver is used. For ex06_2, though, we’re going to keep things simple.

In ex06_2, we’re going to rewrite ex06_1 to exchange Java objects between the client and server instead of XML. Java objects, you ask? Isn’t this REST? Well, there’s no reason a Java object can’t be a valid representation of a resource! If you’re exchanging Java objects, you can still realize a lot of the advantages of REST and HTTP. You still can do content negotiation (described in Chapter 8) and HTTP caching (described in Chapter 10).

The Content Handler Code

For our Java object content handler, we’re going to write one class that is both a MessageBodyReader and a MessageBodyWriter:


public class JavaMarshaller
                     implements MessageBodyReader, MessageBodyWriter

The JavaMarshaller class is annotated with @Provider, @Produces, and @Consumes, as required by the specification. The media type used by the example to represent a Java object is application/x-java-serialized-object:[28]

 public boolean isReadable(Class type, ...

The best content for your career. Discover unlimited learning on demand for around $1/day.