users@jersey.java.net

[Jersey] Re: dinamyc content type

From: Jakub Podlesak <jakub.podlesak_at_oracle.com>
Date: Fri, 19 Aug 2011 10:59:53 +0200

Hi Jose,

the standard (JAX-RS) way to obtain information
on "negotiated" media type(s)/language(s)/encoding(s)
is via the Request.selectVariant method (see [1]).

It returns the most suitable Variant (see [2]) from the given list.

Usage is as follows:

@Path("foo")
public class FooResource {

   @Context Request request;

   @GET
   public Response getMethod() {

     // the list could be pre-calculated, individual variants could be
instantiated and added separately
     List<Variant> supportedVariants =
Variant.mediaTypes(supMT).encodings(supE).languages(supL).add().build();

     Variant selectedVariant = request.selectVariant(supportedVariants);

     if (selectedVariant != null) return ... // response built based on
the selected variant
     else return ... // response signaling the client asked unsupported
variant
   }
}

HTH,

~Jakub

[1]http://jsr311.java.net/nonav/releases/1.1/javax/ws/rs/core/Request.html#selectVariant%28java.util.List%29
[2]http://jsr311.java.net/nonav/releases/1.1/javax/ws/rs/core/Variant.html





On 11.8.2011 16:04, Jose Antonio Illescas Del Olmo wrote:
> How to set content type dinamically?
>
> @GET
> @Produces({"application/xml","text/html","text/plain"})
> public Response get(...) {
> Response.ok(something).type(?).build();
> }
>
> Any solution without split method and use @Produces with single type?
> => It's ugly...
>
> @GET
> @Produces("application/xml")
> public Response getXML(...) {
> Response.ok(something).type("application/xml").build();
> }
>
> @GET
> @Produces("text/html")
> public Response getHTML() {
> Response.ok(something).type("text/html").build();
> }
>
> @GET
> @Produces("text/plain")
> public Response getTEXT() {
> Response.ok(something).type("text/plain").build();
> }
>
> Can get the "default" contentType selected by Jersey on my method?
>
> Please note that Jersey (and any JAX-RS implementation) calculates
> the content type to invoke the method with valid media type...