1

I wanna use the same restful webservice path to produce xml or json, or a xml with xsl header. Is it possible using any framework(jersey or resteasy) in java? Eg:

@Path("/person")
public class PersonService {

    @GET
    @Path("/find")
    public Person find(@QueryParam("name") String name, @QueryParam("outputformat") String outputformat) {
            // do some magic to change output format
            return dao.findPerson(name);
    }
}
AlanNLohse
  • 43
  • 1
  • 6

3 Answers3

3

Maybe you can write a servlet filter that takes the query string and uses it to set the request's accept header accordingly, then jersey should dispatch to whatever method is annotated with @Consumes that matches.

For example, servlet filter intercepts request "?outputFormat=xml" and sets the Accept header to "application/xml". Then, jersey should dispatch to whichever method in your resource is annotated with: @Consumes("application/xml")

This question might help: REST. Jersey. How to programmatically choose what type to return: JSON or XML?

Community
  • 1
  • 1
Upgradingdave
  • 12,916
  • 10
  • 62
  • 72
1

You could also easily customize Jersey ServletContainer and you won't require another param to pass along. You could negotiate representation using .json or .xml in your URL.

public class MyServletContainer extends ServletContainer {

  @Override
  protected void configure(ServletConfig servletConfig, ResourceConfig resourceConfig, WebApplication webApplication) {
    super.configure(servletConfig, resourceConfig, webApplication);
    resourceConfig.getMediaTypeMappings().put("json", MediaType.APPLICATION_JSON_TYPE);
    resourceConfig.getMediaTypeMappings().put("xml", MediaType.APPLICATION_XML_TYPE);
  }

}

In your web.xml, you could define the custom servlet as shown below.

  <servlet>
    <servlet-name>Jersey Web Application</servlet-name>
    <servlet-class>com.sun.jersey.MyServletContainer</servlet-class>
    <init-param>
      <param-name>javax.ws.rs.Application</param-name>
      <param-value>com.sun.jersey.MyWebApplication</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
Arul Dhesiaseelan
  • 2,009
  • 23
  • 19
0

You could use Jersey and use the annotation @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}). You would need to add a mapping feature for POJOs in your application as well. The include in the web.xml file would be

<filter>
    <init-param>
        <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>

Other configurations would be necessary, but it is all in the documentation http://jersey.java.net/nonav/documentation/latest/user-guide.html

James
  • 427
  • 3
  • 5
  • 15