Last active
July 2, 2019 11:06
-
-
Save sathish-io/6587432 to your computer and use it in GitHub Desktop.
REST/Jersey - Content negotiation via URI extensions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
If you have REST service that wanted to return both JSON & XML type, then one way is to set media type in the REST HTTP request header in "Accept" field | |
Setting media type in HTTP header: | |
GET /books/123 | |
Accept: application/json (or application/xml) | |
Other way is to set the return type in URI extensions as, | |
GET /books/123.json - to return json format | |
GET /books/123.xml - to return xml format | |
How to configure Jersey to support URI extensions for content type ? | |
If you are using Jersey < 2.0 then, URI extensions for media type can be done as mentioned in blog - http://zcox.wordpress.com/2009/08/11/uri-extensions-in-jersey/ | |
If you use Jersey 2.x then, the way to do is configure param "jersey.config.server.mediaTypeMapping" in web.xml file, | |
Sample web.xml | |
----------------- | |
<servlet> | |
<servlet-name>Todos</servlet-name> | |
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> | |
<init-param> | |
<param-name>jersey.config.server.mediaTypeMappings</param-name> | |
<param-value>txt : text/plain, xml : application/xml, json : application/json</param-value> | |
</init-param> | |
<load-on-startup>1</load-on-startup> | |
</servlet> | |
This uses filter class: org.glassfish.jersey.server.filter.UriConnegFilter that is implementation of javax.ws.rs.container.ContainerRequestFilter Interface. I noticed that this filter is enabled by default. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment