Java Reference
In-Depth Information
We also annotate getCustomer() with the annotation. This an-
notation tells JAX-RS which HTTP Content-Type the GET response will be. In this case, it
is application/xml .
In the implementation of the method, we use the id parameter to query for a Customer ob-
ject in the customerDB map. If this customer does not exist, we throw the . This exception will set the HTTP response code
to 404, “Not Found,” meaning that the customer resource does not exist. We'll discuss more
about exception handling in Chapter 7 , so I won't go into more detail about the WebApplica-
tionException here.
We will write the response manually to the client through a . In
JAX-RS, when you want to do streaming manually, you must implement and return an in-
stance of the interface from your JAX-RS method.
StreamingOutput is a callback interface with one callback method, write() :
package javax . ws . rs . core ;
public interface
interface StreamingOutput
StreamingOutput {
public void
void write ( OutputStream os ) throws
throws IOException ,
WebApplicationException ;
In the last line of our getCustomer() method, we implement and return an inner class im-
plementation of StreamingOutput . Within the write() method of this inner class, we del-
egate back to a utility method called outputCustomer() that exists in our CustomerRe-
source class. When the JAX-RS provider is ready to send an HTTP response body back
over the network to the client, it will call back to the write() method we implemented to
output the XML representation of our Customer object.
In general, you will not use the StreamingOutput interface to output responses. In
Chapter 6 , you will see that JAX-RS has a bunch of nice content handlers that can automatic-
ally convert Java objects straight into the data format you are sending across the wire. I
didn't want to introduce too many new concepts in the first introductory chapter, so the ex-
ample only does simple streaming.
Updating a customer
The last RESTful operation we have to implement is updating customers. In Chapter 2 , we
used PUT /customers/{id} , while passing along an updated XML representation of the
customer. This is implemented in the updateCustomer() method of our CustomerResource
Search WWH ::

Custom Search