Java Reference
In-Depth Information
A GET request returns the HTTP status code 200 for a successful request. The @Pro-
duces annotation identifies to the client the MIME type of the response. In this case I
want to return JSON or XML:
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
The annotation accepts an array of MediaType instances, which are used for content ne-
gotiation based on the Accept header in the incoming request.
If I want to specify the response header, JAX-RS provides a factory class called Re-
sponse using the builder design pattern. Here's the implementation of the findById
method that uses it:
@GET @Path("{id}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response findById(@PathParam("id") long id) {
return Response.ok(dao.findById(id))
.build();
}
The ok method on the Response class sets the response status code to 200. It takes an
object as an argument, which is added to the response. The @PathParam annotation also
converts the input ID from a string to a long automatically.
Inserting a new instance is a bit more complicated, because the newly inserted instance
needs its own URI. Because in this case the generated URI will contain an ID generated by
the database, the resource method is tied to HTTP POST requests, which are neither safe
nor idempotent.
Implementation detail
The create method returns a URL that includes the primary key from the database table.
That detail is not something you want to expose to the client. Some unique identifier is re-
quired; here the ID is used for simplicity.
The new URI is added to the response as part of its Location header. The new URI is
generated using the UriBuilder class from JAX-RS, based on the incoming URI:
Search WWH ::




Custom Search