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

Chapter 6. JAX-RS Content Handlers

Last chapter, we focused on injecting information from the header of an HTTP request. In this chapter, we will focus on the message body of an HTTP request and response. In the examples in the previous chapters, we used low-level streaming to read in requests and write out responses. To make things easier, JAX-RS also allows you to marshal message bodies to and from specific Java types. It has a number of built-in providers, but you can also write and plug in your own providers. Let’s look at them all.

Built-in Content Marshalling

JAX-RS has a bunch of built-in handlers that can marshal to and from a few different specific Java types. While most are low-level conversions, they can still be useful to your JAX-RS classes.

javax.ws.rs.core.StreamingOutput

We were first introduced to StreamingOutput back in Chapter 3. StreamingOutput is a simple callback interface that you implement when you want to do raw streaming of response bodies:

public interface StreamingOutput  {
      void write(OutputStream output) throws IOException,
                                             WebApplicationException;
}

You allocate implemented instances of this interface and return them from your JAX-RS resource methods. When the JAX-RS runtime is ready to write the response body of the message, the write() method is invoked on the StreamingOutput instance. Let’s look at an example:

@Path("/myservice") public class MyService { @GET @Produces("text/plain") StreamingOutput get() { return new StreamingOutput() { public void write(OutputStream ...

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