Java Reference
In-Depth Information
First I'll add the links to the HTTP headers and show how to use them. Then I'll use struc-
tural links instead, using the JAXB serializer. Finally, I'll take control of the output gener-
ation process and customize the output writer using Groovy's JsonBuilder .
9.5.2. Adding transitional links
To create transitional links, the JAX-RS API starts with the inner class Response
.Response-Builder in the javax.ws.rs.core package. ResponseBuilder
has three relevant methods:
public abstract Response.ResponseBuilder link(String uri, String rel)
public abstract Response.ResponseBuilder link(URI uri, String rel)
public abstract Response.ResponseBuilder links(Link... link)
The first two add a single Link header to the HTTP response. The third adds a series of
headers to the response. Here's an example from the PersonResource class:
@GET @Produces(MediaType.APPLICATION_JSON)
Response findAll() {
def people = dao.findAll();
Response.ok(people).link(uriInfo.requestUri, 'self').build()
}
The link method in this case uses the request URI as the first argument and sets the rel
property to self . The corresponding test accesses the link as follows:
def 'get request returns all people'() {
when:
def response = client.get(path: 'people')
then:
response.status == 200
response.contentType == 'application/json'
response.headers.Link ==
'<http://localhost:1234/people>; rel="self"'
}
This example returns only a single Link header. For multiple links (for example, the
three transitional links prev , next , and self for each individual person), the method
getHeaders('Link') retrieves them all.
Search WWH ::




Custom Search