users@jersey.java.net

Re: [Jersey] produce multiple resource types in a single method

From: Paul Sandoz <Paul.Sandoz_at_Sun.COM>
Date: Mon, 26 Oct 2009 13:19:11 +0100

On Oct 26, 2009, at 12:16 PM, Dário Abdulrehman wrote:

> Hi,
>
> When a resource method produces several response types how do you
> actually construct each response type?
>
> For example, given:
>
> @GET
> @Produces({"application/json", "application/xml"})
> public Response doGet(@QueryParam("x") String x) {
>
> }
>
> How do you know if you should construct a response with JSON or
> plain XML?

Unfortunately it will require that look at the acceptable headers
(from HttpHeaders) and compare against those declared in @Produces.

I thought that the Content-Type of the response would have been set
before the method call, but investigation of the code showed this was
not the case. I am investigating fixing that so that you could do:

   @GET
   @Produces({"application/json", "application/xml"})
   public Response doGet(@QueryParam("x") String x, @Context
HttpContext hc) {
     MediaType contentType = hc.getResponse().getMediaType();
   }



> Is there any alternative to creating several doGet methods
> (doGetAsJSON doGetAsXML, etc...), each with a single @Produces
> annotation for each return type?
>

IMHO if you need to do an if/else dependent on the actual media type
produced it may be better to have separate methods. (although that may
depend if you are deferring to a third party library or not).

If the entity returned in the response is abstracted from the media
type then an appropriate message body writer can be selected given the
Java type and media type.

Paul.