O'Reilly logo

RESTful Java with JAX-RS by Bill Burke

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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:

src/main/java/com/restfully/shop/services/JavaMarshaller.java

@Provider
@Produces("application/x-java-serialized-object")
@Consumes("application/x-java-serialized-object")
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, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required