Java Reference
In-Depth Information
bookmarkable URIs. So you've decided that your URI scheme will be ...user/{id} , which
is a template where the part between the curly braces represents the user's ID. So if you create
a user with ID 007, that bookmarkable URI will be ...resources/forms/user/007 .
NOTE
To follow the basic REST style, you need to create this URI now so that you can return in the HTTP
response the Location header populated with the value of the unique URL for the user you created.
This provides the client with metadata about the response and also a choice for the client to transition
state (among others). Remember, hypermedia as the engine of application state.
So in order to build your URI, use the UriBuilder class in conjunction with the UriInfo ob-
ject, which was injected into the method via the @Context parameter to this method. Again,
you don't have to do anything special to get that UriInfo object; its values are populated by
the runtime.
Using the UriInfo instance, you get the value for the path the current request is answering,
and then use the path method to indicate to your template that you need to populate ( "{a}" ).
The value within the template (in this case, a ) is not special. It gets substituted for the value
passed to the build method (in this case, the ID of the user you created). Note that the
UriBuilder class follows a standard builder pattern, and works like StringBuilder and oth-
er builder classes ( ResponseBuilder in JAX-RS, for instance).
Once your URI is created, pass it into your response-building process. The Response class
actually has ResponseBuilder as an inner class. By using the created method initially, you
set the HTTP response code to 201 Created. By using the entity method and passing it your
user object (the entity you created), you're able to return the representation of the entity along
with the response. The runtime will look for an available MessageBodyWriter<User> imple-
mentation in order to create that entity representation. Finally, by using the location method,
you can automatically add the new URI as the value of the Location header in the HTTP re-
sponse.
Note that it's enough to simply post the form to itself by specifying action='' because you
have different HTTP methods answering. While there are two GETs in the service, they re-
spond to different paths, as the viewOne method only responds when an ID is supplied.
The last class in this little service is the MessageBodyWriter implementation that returns your
User representation as requested by your invocation of the entity method on the Response
builder. The writer is shown in Example 8-22 .
Example8-22.UserHtmlWriter.java creates an HTML representation of the user entity
Search WWH ::




Custom Search