users@jersey.java.net

Re: Jersey setting the content type in the Response

From: Jakub Podlesak <jakub.podlesak_at_oracle.com>
Date: Thu, 18 Nov 2010 18:42:49 +0100

Hi,

If you want to return String in all cases, than the only issue is to
determine
the negotiated content media type based on the client request accept header.

The following code snippet shows how to do that using the selectVariant
function:

----8<----
     static final MediaType[] supportedMediaTypes =
{MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_XML_TYPE};

     static final List<Variant> mtVariantList =
getVariantList(supportedMediaTypes);

     // this is just a substitute for your convertors
     Map<MediaType, String> results = new HashMap<MediaType, String>(){{
        put(MediaType.APPLICATION_JSON_TYPE, "{\"format\":\"json\"}");
        put(MediaType.APPLICATION_XML_TYPE, "<format>xml</format>");
     }};

     static List<Variant> getVariantList(MediaType[] mt) {
         Variant.VariantListBuilder b =
Variant.VariantListBuilder.newInstance();
         for (MediaType t : mt) {
             b.mediaTypes(t).add();
         }
         return b.build();
     }

     @GET
     @Path("chameleon")
     public String getIt(@Context Request req) {
         final MediaType mediaType =
req.selectVariant(mtVariantList).getMediaType();
         return results.get(mediaType);
     }

---->8----

HTH,

~Jakub




On 11/09/2010 07:14 PM, rahul.babbar1_at_gmail.com wrote:
> Hi,
>
> Here is my situation.
>
> 1) The generation of appropriate format (XML/JSON etc) is custom and
> not
> JAXB based so that i have my own convertor to convert objects to these
> format.
> 2) So, according to the above case, i need to return String in all the
> GET
> methods in my Servlet for handling the requests.
> 3) However i need to set the appropriate Content Type in the response
> so
> that the browser can interpret it.
> 4) My GET methods are annotated with @Produces({MediaType.TEXT_XML,
> MediaType.APPLICATION_JSON}) so that these are the applicable types
> which
> can be returned.
> 5) Before returning the String in the method, i am setting the
> appropriate
> Content Type in the response(I am injecting HttpServletResponse in my
> REST
> service class ).
>
> However, in all the cases, Jersey returns the String with content Type
> set
> in response as MediaType.TEXT_XML.
> If i annotate the method with @Produces({MediaType.APPLICATION_JSON,
> MediaType.TEXT_XML}), it sets the content type as
> MediaType.APPLICATION_JSON, so its setting the first media type.
>
> Can someone help me out of here?
>