【发布时间】: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 来做到这一点?
一些建议:
- 使用一些静态方法返回json:Return JSON or View from Spring MVC Controller
- 使用响应实体In Spring MVC, how can I set the mime type header when using @ResponseBody
- 使用默认视图: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
}
建议和/或方向将不胜感激!
【问题讨论】:
标签: java json spring spring-mvc