Wiki Markup |
---|
{span:style=font-size:2em;font-weight:bold} JAX-RS : Understanding the Basics {span} |
Table of Contents |
---|
What is New in JAX-RS 2.0
...
Either javax.ws.rs.core.Response or custom type can be returned. javax.ws.rs.core.Response can be used to set the HTTP response code, headers and entity. JAX-RS MessageBodyWriters (see below) are in charge of serializing the response entities, those which are returned directly or as part of javax.ws.rs.core.Response.
Response Streaming
JAX-RS StreamingOutput
StreamingOutput can be used to stream the data to the client, for example:
Code Block | ||||
---|---|---|---|---|
| ||||
@GET
@Path("/books/pdf")
@Produces("application/pdf")
public StreamingOutput getPdf() {
return new StreamingOutput() {
public void write(final OutputStream os) {
// read chunks of data from PDF and write to OutputStream
}
};
}
|
CXF StreamingResponse
CXF 3.0.0 introduces StreamingResponse extension. It can be used with the WebSocket transport or as a possible replacement for the code working with StreamingOutput.
For example, consider that a number of resources need to be returned as they become available:
Code Block | ||||
---|---|---|---|---|
| ||||
@GET
@Path("/books")
@Produces("application/xml")
public StreamingResponse<Book> getBooks() {
return new StreamingResponse<Book>() {
public void writeTo(final Writer<Book> writer) {
writer.getEntityStream().write("<Books>".getBytes());
writer.write(new Book("CXF"));
writer.write(new Book("JAX-RS"));
writer.getEntityStream().write("</Books>".getBytes());
}
};
}
|
Exception handling
One can either throw an unchecked WebApplicationException or return Response with a proper error code set.
The former option may be a better one when no JAX-RS types can be added to method signatures.
...