【问题标题】:Is there a way to change the output type for restful webservices by a parameter in java?有没有办法通过java中的参数更改restful webservices的输出类型?
【发布时间】:2013-02-01 17:41:59
【问题描述】:

我想使用相同的静态 web 服务路径来生成 xml 或 json,或带有 xsl 标头的 xml。 是否可以在 java 中使用任何框架(jersey 或 resteasy)? 例如:

@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);
    }
}

【问题讨论】:

    标签: java format jersey resteasy restful-architecture


    【解决方案1】:

    也许您可以编写一个 servlet 过滤器,该过滤器接受查询字符串并使用它来相应地设置请求的接受标头,然后球衣应该分派到任何带有 @Consumes 注释的匹配方法。

    例如,servlet 过滤器拦截请求“?outputFormat=xml”并将 Accept 标头设置为“application/xml”。然后,jersey 应该分派到资源中带有注释的任何方法:@Consumes("application/xml")

    这个问题可能会有所帮助:REST. Jersey. How to programmatically choose what type to return: JSON or XML?

    【讨论】:

    • 谢谢!这就是我需要的。
    • 太好了,很高兴为您提供帮助。随意投票和/或接受答案。
    【解决方案2】:

    您还可以轻松自定义 Jersey ServletContainer,并且不需要传递其他参数。您可以在 URL 中使用 .json 或 .xml 协商表示。

    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);
      }
    
    }
    

    在您的 web.xml 中,您可以定义自定义 servlet,如下所示。

      <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>
    

    【讨论】:

      【解决方案3】:

      您可以使用 Jersey 并使用注释 @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})。您还需要在应用程序中为 POJO 添加映射功能。 web.xml 文件中的包含将是

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

      其他配置是必要的,但都在文档http://jersey.java.net/nonav/documentation/latest/user-guide.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-13
        • 1970-01-01
        • 2013-01-25
        • 1970-01-01
        • 2021-03-19
        相关资源
        最近更新 更多