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:43:44 +0100

On Oct 26, 2009, at 1:40 PM, Marc Hadley wrote:

> On Oct 26, 2009, at 8:19 AM, Paul Sandoz wrote:
>>>
>>> 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.
>>
> Use the JAX-RS support for dynamic content negotiation:
>
> @GET
> @Produces({"application/json", "application/xml"})
> public Response doGet(@Context Request req) {
> MediaType types[] = {"application/json", "application/xml"};
> List<Variant> vars = Variant
> .mediaTypes(types)
> .add()
> .build();
> Variant var = req.selectVariant(vars);
> SomeClass body = ...;
> return Response.ok()
> .entity(body).type(var.getMediaType()).build();
> }
>
> This will do the comparison of available and acceptable media types
> for you and select the best match.
>

I forgot about that!

Paul.

> Marc.
>
>
>> 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.
>>
>> ---------------------------------------------------------------------
>> To unsubscribe, e-mail: users-unsubscribe_at_jersey.dev.java.net
>> For additional commands, e-mail: users-help_at_jersey.dev.java.net
>>
>
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: users-unsubscribe_at_jersey.dev.java.net
> For additional commands, e-mail: users-help_at_jersey.dev.java.net
>