Reputation: 4411
I have set up my controller so that it will return the data in the format as requested through HTTP Accept-Type header set by the client:
<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>
Sample controller method:
@RequestMapping(value = "/test", method = RequestMethod.POST)
@ResponseBody
public TestObject executeTest()
{
TestObject t = ...
// not important, generating t
return t;
}
so for example they will do: http:// someurl/test
It works perfectly just fine if the client can actually set Accept-Type. Now that's where the issue starts when client is unable to set Accept-Type header, I would rely on the url to be suffixed, for example:
My challenge is how to configure Spring properly to do this?
Some suggestions:
and many others, but none of the solution seem to be able to satisfy what I need in a nice, clean why. Ideally I would like to be able to do something clean like
@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
}
Suggestions and/or directions would be greatly appreciated!
Upvotes: 0
Views: 2486
Reputation: 17361
Spring MVC 3.0+ introduced the ContentNegotiatingViewResolver
which has the exact functionality you seek.
Implementation of ViewResolver that resolves a view based on the request file name or Accept header.
This blogpost can help you on your way: http://blog.springsource.org/2013/06/03/content-negotiation-using-views/
Upvotes: 2
Reputation: 3151
You could use the @Produces annotation, introduced with spring 3.1. Have a look at the actual docs http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-ann-requestmapping-produces and in the Spring Jira ( https://jira.springsource.org/browse/SPR-7213 ) for some background
Upvotes: 0