Java Reference
In-Depth Information
4. The runtime checks to make sure that it can use an available provider to create a response.
It finds the
@Produces
annotation with a value of
text/html
, and checks its
isWriteable
method to see whether the invoked method parameter (
List<Product>
) matches. It does,
so the runtime selects the
ProductHtmlFormWriter
class to create its response.
5. The writer's
writeTo
method gets invoked to write the HTML response containing the
empty form to the output stream.
Now that you've written the response to the browser, the user can fill out the form to add a
product. Here's the sequence of events:
1. Once the user fills out the form and clicks Submit, the runtime determines that it needs to
read the incoming response because its
@Consumes
annotation declares that it is a handler
for the
application/x-www-form-urlencoded
MIME type.
2. The runtime further determines that your
ProductHtmlFormReader
class is the appro-
priate handler because it implements
MessageBodyReader<List<Product>>
. It does this
with the
isReadable
method, which finds that the matching type is a
List
.
3. Your helper methods in this
Reader
class then break up the incoming request into a single
string and parse that string for the form data. Form data is separated in HTML with am-
persands (&) and can be inspected as key/value pairs. So once you parse that, you can
create a new
Product
instance using the submitted data.
4. The reader method then adds the new product to the list that it's maintaining of all ordered
products.
5. The runtime returns control to the
Resource
class and invokes its
addToOrder
method,
which is mostly a pass-through.
6. You still have to write a response, so the runtime invokes your same
ProductHtm-
lFormWriter
class and returns the form. Because the writer receives the list of products
from the resource, it can append to the bottom of the form something new: the previously
ordered products. The HTML is written and returned to the output stream.
Now we'll look at the rest of the classes that make up the application. The
Mes-
sageBodyWriter
implementation is shown in
Example 8-35
.
Classes that implement the
MessageBodyReader<T>
and
MessageBodyWriter<T>
interfaces
are called entityproviders. Their job is to map representations to their associated Java types.
The runtime uses the reader entity provider to map HTTP requests, and the writer is used to
map HTTP responses.
Example8-35.ProductHtmlFormWriter.java