jersey rest web services multiple format
how to return the correct representation based on URI
example
/text.json should return json
/text.xml should return xml
/text should return plain text
All these are mapped to the same method
@GET public Contact getContacts开发者_StackOverflow中文版() {
}
The answer can be found in this post: http://jersey.576304.n2.nabble.com/extension-custom-negotiation-td3078866.html
Essentially you configure a ResourceConfig https://jersey.dev.java.net/nonav/apidocs/1.1.0-ea/jersey/com/sun/jersey/api/core/ResourceConfig.html
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>
....
精彩评论