Wednesday, January 11, 2012

JAX-RS Tip of the Day: Use Response to wrap... Responses

One of the really nice features of JAX-RS is the ability to implement fine grained control over the response returned from the server based on the client request. The Response.ResponseBuilder gives us incredible flexibility to generate the response. Since it uses the builder pattern, it is easy to daisy-chain the information we want into a custom response.

I would highly recommend that you consider returning a custom response for all requests. I would like to explain with an example. I would like to perform a @POST request where I am creating a new object on the server. Since it is a HTTP 1.1 request, I look at Hypertext Transfer Protocol -- HTTP/1.1 (RFC-2616) to see what I must, should, and may return. The difference in the word choices has specific meaning in the specification. In my case, I would like to be completely compliant.

10.2.2 201 Created
The request has been fulfilled and resulted in a new resource being created. The newly created resource can be referenced by the URI(s) returned in the entity of the response, with the most specific URI for the resource given by a Location header field. The response SHOULD include an entity containing a list of resource characteristics and location(s) from which the user or user agent can choose the one most appropriate. The entity format is specified by the media type given in the Content-Type header field. The origin server MUST create the resource before returning the 201 status code. If the action cannot be carried out immediately, the server SHOULD respond with 202 (Accepted) response instead.
A 201 response MAY contain an ETag response header field indicating the current value of the entity tag for the requested variant just created, see section 14.19.

OK, the basic response must return 201 - Created status, and a Location header. It should contain an entity (which may only be entity-headers) and may contain an ETag. This is all very easy to do with Jersey. As you can see from the code snippet, we read the @FormParam information from a form, and create an object which we add to a List<Widget%gt; objects signified by the ws.add(widget) we get the index value for use in our URI. Next we create a URI from our request, and add a path to it for our index.

Finally we use Apache Commons Codec Hex to generate a hex string for our ETag. Finally this is all combined in a Response sent back to the client. This can be seen below.


Popular Posts