Java Reference
In-Depth Information
Setting Metadata on Representations
Problem
You want to follow the RESTful principle of setting metadata on representations you return to
clients.
Solution
Use the
Response
and
ResponseBuilder
classes to set your metadata using some of their
built-in methods.
Discussion
One of the tenets of REST is that representations can include metadata. In JAX-RS, this idea
is enabled by the
ResponseBuilder
class, which is an inner class of
Response
. The build pat-
tern employed by this class means that a modified instance of
Response
is returned by each
invocation so that you can append any amount of metadata you need to, one item at a time.
Here's an example:
@POST
public Response addUser(...) {
User user = ...
URI userId = UriBuilder.fromResource(User.class)...
return Response.created(userId).build();
}
The use of the
created
method here modified the response by setting the HTTP status
code to 201 Created.
Table 8-1
highlights the metadata methods available from
Re-
sponse.ResponseBuilder
.