Java Reference
In-Depth Information
The target , type , genericType , annotations , and mediaType parameters of the
writeTo() method are the same information passed into the getSize() and isWriteable()
methods. The httpHeaders parameter is a javax.ws.rs.core.MultivaluedMap that rep-
resents the HTTP response headers. You may modify this map and add, remove, or change
the value of a specific HTTP header as long as you do this before outputting the response
body. The outputStream parameter is a java.io.OutputStream and is used to stream out
the data.
Our implementation simply creates a JAXBContext using the type parameter. It then creates
a javax.xml.bind.Marshaller and converts the Java object to XML.
Adding pretty printing
By default, JAXB outputs XML without any whitespace or special formatting. The XML
output is all one line of text with no new lines or indentation. We may have human clients
looking at this data, so we want to give our JAX-RS resource methods the option to pretty-
print the output XML. We will provide this functionality using an @Pretty annotation. For
example:
@Path ( "/customers" )
public
public class
class CustomerService
CustomerService {
@GET
@Path ( "{id}" )
@Produces ( "application/xml" )
@Pretty
public
public Customer getCustomer ( @PathParam ( "id" ) int
int id ) {...}
}
Since the writeTo() method of our MessageBodyWriter has access to the getCustomer()
method's annotations, we can implement this easily. Let's modify our JAXBMarshaller
class:
public
public void
void writeTo ( Object target ,
Class <?> type ,
Type genericType ,
Annotation [] annotations ,
MediaType mediaType ,
MultivaluedMap < String , Object > httpHeaders ,
OutputStream outputStream ) throws
throws IOException
{
try
try {
JAXBContext ctx = JAXBContext . newInstance ( type );
Marshaller m = ctx . createMarshaller ();
Search WWH ::




Custom Search