users@jersey.java.net

Re: [Jersey] Multiple resource formats

From: Farrukh Najmi <farrukh_at_wellfleetsoftware.com>
Date: Fri, 30 Jan 2009 16:46:49 -0500

Marc Hadley wrote:
> On Jan 30, 2009, at 3:32 PM, Farrukh Najmi wrote:
>>
>> I suspect this one has been discussed before but I did not find
>> anything in archives...
>>
>> In me jersey server I want to expose the same resource in multiple
>> output formats. The current thinking is that the format will be
>> specified in the URL as a parameter rather than a path segment of the
>> URL.
>>
>> Thus to get XML response the URL pattern would be:
>>
>> /search?queryId=foo&queryParams1=bar&format=text/xml
>>
>> and to get JSON response the URL pattern would be:
>> /search?queryId=foo&queryParams1=bar&format=application/json
>>
>> This would require having two methods in the server with same @Path
>> but different @Produces annotations:
>>
>> @Path("/search")
>> @GET
>> @Produces("text/xml")
>> public Response searchXML() throws JAXBException {
>> String resp = searchInternal();
>> return Response.status(200).entity(resp).build();//"OK"
>> }
>>
>> @Path("/search")
>> @GET
>> @Produces("application/json")
>> public Response searchJSON() throws JAXBException {
>> String resp = searchInternal();
>> return Response.status(200).entity(resp).build();//"OK"
>> }
>>
>>
>> What I am not sure of is how to specify the "format" parameter for
>> each method.
>>
> You don't need two otherwise identical methods, you can use
> @Produces({""text/xml", "application/json"}) on one method. You can
> extract the format as a method parameter using the @QueryParam
> annotation like this:
>
> public Response searchXML(@QueryParam("format") String format)
>
> When you create the returned Response you'll need to set the media
> type of the entity explicitly like this:
>
> return Response.ok(resp,format).build();
>
> The above is a shorthand equivalent to:
>
> Response.status(200).entity(resp).type(format).build();
>
> The media type is inferred if there's only one type in @Produces but
> if there's more than one possibility you have to specify it in the
> Response.
>

This is just what I needed! Thanks Marc.

BTW, do you have an opinion on use of a format QueryParam vs, request
header. The latter seems the more RESTFul approach but I am not sure how
a human user can specify request header in a URL. Is there a standard
mechanism for encoding HTTP request header param values within a URL? If
not, and if I need a human to be able to specify format in a web browser
then it seems the format QueryParam is my best option.

What do you advice. Thanks and belated happy new year / birthday :-)

-- 
Regards,
Farrukh
Web: http://www.wellfleetsoftware.com