我对Spring MVC相当陌生。今天,当我学习@ResponseBody
,我有一些问题有关HttpMessageConverter
S:@ResponseBody选择不同的响应格式
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
<bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter"/>
<bean class="org.springframework.http.converter.FormHttpMessageConverter"/>
<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
</list>
</property>
</bean>
如上所述,我们可以声明不同的转换器的列表。所以这意味着我们可以选择其中一个作为响应体转换器。
但如何选择一个使用?例如,在functionA()
中返回JSON,然后在functionB()
中返回XML。
我的方法是强制Content-Type
的回应,这是正确的方法吗?还是有更好的解决方案?
public @ResponseBody User getUser(HttpServletResponse response) {
response.setContentType("application/xml");
// SOME CODES HERE
return user;
}
;对生产 “的charset = UTF-8”。 – Walfrat
谢谢,非常清楚的主意!有关更多详细信息,我们只能使用由RequestMappingHandlerAdapter中定义的转换器支持的Contetn类型来设置'produce'?或者它已经支持一些像JSON或String这样的转换器,我们不需要在xml配置文件中显式声明它们? – DONG
每个'HttpMessageConverter'都有一个'getSupportedMediaTypes',它定义了这个转换器可以处理的媒体类型。看看https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/http/converter/HttpMessageConverter.html –