我已经设置了我的 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 来做到这一点?
一些建议:
- 使用一些静态方法返回json:Return JSON or View from Spring MVC Controller
- 使用 ResponseEntity In Spring MVC, how can I set the mime type header when using @ResponseBody
- 使用默认 View :http://blog.safaribooksonline.com/2012/03/28/spring-mvc-tip-returning-json-from-a-spring-controller/
还有许多其他解决方案,但似乎没有一个解决方案能够以一个好的、干净的理由满足我的需求。理想情况下,我希望能够做一些干净的事情,例如
@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/