【问题标题】:Spring return JSON / XML / JSON-P based on suffixSpring根据后缀返回JSON/XML/JSON-P
【发布时间】:2013-08-11 09:50:28
【问题描述】:

我已经设置了我的控制器,以便它以客户端设置的 HTTP Accept-Type 标头请求的格式返回数据:

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
            <ref bean="jacksonJSONMessageConverter" />
            <ref bean="jaxbXMLConverter" />
            <ref bean="jsonpMessageConverter" />
        </list>
    </property>
</bean>

示例控制器方法:

@RequestMapping(value = "/test", method = RequestMethod.POST)
@ResponseBody
public TestObject executeTest()
{
    TestObject t = ...
    // not important, generating t
    return t;
}

例如,他们会这样做:http://someurl/test

如果客户端实际上可以设置 Accept-Type,它就可以完美地工作。现在这就是当客户端无法设置 Accept-Type 标头时问题开始的地方,我将依赖 url 后缀,例如:

  • http://someurl/test.xml
  • http://someurl/test.json
  • http://someurl/test.jsonp?callback=fn

我的挑战是如何正确配置 Spring 来做到这一点?

一些建议:

还有许多其他的,但似乎没有一个解决方案能够以一个漂亮、干净的原因满足我的需求。理想情况下,我希望能够做一些干净的事情,比如

@RequestMapping(value = "/test.xml", method = RequestMethod.POST)
@ResponseBody
public TestObject executeTestReturnXML()
{
    TestObject t = executeTest();

    return t; // somehow magically force Spring converter to convert it to XML
}

@RequestMapping(value = "/test.json", method = RequestMethod.POST)
@ResponseBody
public TestObject executeTestReturnJson()
{
    TestObject t = executeTest();

    return t; // somehow magically force Spring converter to convert it to JSON
}

@RequestMapping(value = "/test.jsonp", method = RequestMethod.POST)
@ResponseBody
public TestObject executeTestReturnJsonP(@RequestParam(value = "callback", required = true) String callback)
{
    TestObject t = executeTest();

    return t; // somehow magically force Spring converter to convert it to JSON-P with callback wrapper
}

建议和/或方向将不胜感激!

【问题讨论】:

    标签: java json spring spring-mvc


    【解决方案1】:

    Spring MVC 3.0+ 引入了 ContentNegotiatingViewResolver,它具有您所寻求的确切功能。

    ViewResolver 的实现,它根据请求文件名或 Accept 标头解析视图。

    这篇博文可以帮到你:http://blog.springsource.org/2013/06/03/content-negotiation-using-views/

    【讨论】:

    • 谢谢!这非常有帮助,我在阅读了两篇博文后就开始使用它了。
    • 如果使用@ResponseBody 注释,ViewResolver 是不相关的。 (我不确定)
    • 你确实是对的。问题是 @ResponseBody 对于给定的目标可能不够灵活。 ContentNegotiatingViewResolver 为您提供了这种灵活性。
    【解决方案2】:

    您可以使用 Spring 3.1 引入的 @Produces 注释。看看实际的文档http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-ann-requestmapping-produces 并在 Spring Jira (https://jira.springsource.org/browse/SPR-7213) 中了解一些背景

    【讨论】:

      猜你喜欢
      • 2017-12-15
      • 2012-08-02
      • 1970-01-01
      • 1970-01-01
      • 2012-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多