Java Reference
In-Depth Information
Interacting with a Resource Using a Custom Reader
and Writer
Problem
You want to create a web page that produces a representation of an item with HTML forms
and allows the user to interact with it. You have a real-world compound object, such as a list
of products, and you want to read and write its representation in an interactive HTML form.
Solution
Create a resource, and then create two classes: one that implements MessageBodyWriter<T>
and another that implements MessageBodyReader<T> . Use the @Produces and @Consumes
annotations on them respectively. In the writer, produce the HTML form; in the reader, parse
the incoming form data and create your objects with them.
This gets complex fairly quickly, so we'll look at a complete example in the discussion below.
This example uses only JAX-RS standard code, so it's portable across implementations. I'm
using Jersey here, but this would work in JBoss RESTEasy too.
Discussion
This application consists of four classes: a Product class that is a POJO containing two strings
and an integer; a REST Resource class that manages the resource on the server; a Mes-
sageBodyWriter implementation that writes out the HTML form; and a MessageBodyReader
implementation that gathers the form data and creates Product instances from it.
Figure 8-4 shows a screenshot of the application running in Tomcat, after submitting the form
a few times. Open your browser to http://localhost:8080/restexamples/resources/order after
deploying the application to see it working.
Search WWH ::




Custom Search