java - Spring根据后缀返回JSON/XML/JSON-P

标签 java json spring spring-mvc

我已经设置了我的 Controller ,以便它将按照客户端设置的 HTTP Accept-Type header 请求的格式返回数据:

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

Controller 方法示例:

@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 header 时,问题就开始了,我将依赖于要添加后缀的 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
}

建议和/或指导将不胜感激!

最佳答案

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

Implementation of ViewResolver that resolves a view based on the request file name or Accept header.

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

关于java - Spring根据后缀返回JSON/XML/JSON-P,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18147102/

相关文章:

java - Play Framework 应用程序默认使用多少最大堆空间

andOperator 的 Spring Mongo 标准问题

java - Spring AOP 切入点表达式排除特定的返回类型或参数

java - springboot应用程序编译错误

java - 如何使用表内的数据之一获取 firebase 表中的所有信息

java - WindowBuilder问题

javascript - 如何访问名称中有空格的 Json 对象?

java - 通过 GlassFish 服务器使用 REST - 如何允许使用 HTML 输入更新列表并返回 JSON 对象?

javascript - JSON.parse 在有效 Json 上失败。已转义控制字符。如果

spring - spring 中 jpa 实体的自动扫描包