users@jersey.java.net

Re: [Jersey] extension custom negotiation

From: Paul Sandoz <Paul.Sandoz_at_Sun.COM>
Date: Tue, 16 Jun 2009 13:11:58 +0200

On Jun 14, 2009, at 12:45 AM, James Lorenzen wrote:

> How do you handle extension custom negotiation like foo.xml or
> foo.json automatically in jersey?
> I can't find any documentation on it. The only thing I have found is
> this thread, https://jersey.dev.java.net/servlets/ReadMsg?list=users&msgNo=2718
> , that references this issue, https://jersey.dev.java.net/issues/show_bug.cgi?id=108
> .
>
> My guess is the client calls foo.json.
> The REST method has two @Produces mime types for xml and json.
>
> @Produces({"application/xml", "application/json"}
>
> But how does the method know which one was requested by the client?
>

You need to extend an implementation of ResourceConfig [1] and
override the media type mappings method.

For example you can do the following:

package foo;

public class MyResourceConfig extends PackagesResourceConfig {
     public PackagesResourceConfig(Map<String, Object> props) {
         super(props);
     }

     public Map<String, MediaType> getMediaTypeMappings() {
         Map<String, MediaType> m = new HashMap<String, MediaType> ();
         m.put("json", MediaType.APPLICATION_JSON_TYPE);
         m.put("xml", MediaType.APPLICATION_XML_TYPE);
         return m;
     }
}

and you can register your "MyResourceConfig" as described here:

   https://jersey.dev.java.net/documentation/1.1.0-ea/user-
guide.html#d4e115

In the above example your web.xml would need to container:

<web-app>
      <servlet>
          <servlet-name>Jersey Web Application</servlet-name>
          <servlet-
class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-
class>
          <init-param>
              <param-name>javax.ws.rs.Application</param-name>
              <param-value>foo.MyResourceConfig</param-value>
          </init-param>
          <init-param>
              <param-name>com.sun.jersey.config.property.packages</
param-name>
              <param-value>org.foo.rest;org.bar.rest</param-value>
          </init-param>
      </servlet>
      ....

Paul.

[1] https://jersey.dev.java.net/nonav/apidocs/1.1.0-ea/jersey/com/sun/jersey/api/core/ResourceConfig.html

[2] https://jersey.dev.java.net/nonav/apidocs/1.1.0-ea/jersey/com/sun/jersey/api/core/ResourceConfig.html
#getMediaTypeMappings()