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.
HTH,
Marc.
> Thanks for your help.
>
> --
> Regards,
> Farrukh
>
> Web: http://www.wellfleetsoftware.com
>
>
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: users-unsubscribe_at_jersey.dev.java.net
> For additional commands, e-mail: users-help_at_jersey.dev.java.net
>
---
Marc Hadley <marc.hadley at sun.com>
CTO Office, Sun Microsystems.