2016-04-14 129 views
0

我对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; 
} 

回答

1

但是如何选择一个使用?例如,在泛函()来 返回JSON,然后在functionB()返回XML

您可以使用RequestMappingproduces属性为:

@RequestMapping(value = "/a", produces = "application/json") 
public @ResponseBody Something functionA() { ... } 

和:

@RequestMapping(value = "/b", produces = "application/xml") 
public @ResponseBody Something functionB() { ... } 

此外,您可以省略produces在您接受客户接受的内容时可以更自由。通过这种方法,您可以让客户在XML,JSON之间进行选择,或通过称为的过程进行内容协商使用Accept标头。事实上,如果客户端火象的请求:

GET /a HTTP/1.1 
Accept: application/json 

functionA将返回返回值的JSON表示,如果客户端发送该请求:

GET /a HTTP/1.1 
Accept: application/xml 

functionA将返回的XML表示返回值。

+1

;对生产 “的charset = UTF-8”。 – Walfrat

+0

谢谢,非常清楚的主意!有关更多详细信息,我们只能使用由RequestMappingHandlerAdapter中定义的转换器支持的Contetn类型来设置'produce'?或者它已经支持一些像JSON或String这样的转换器,我们不需要在xml配置文件中显式声明它们? – DONG

+0

每个'HttpMessageConverter'都有一个'getSupportedMediaTypes',它定义了这个转换器可以处理的媒体类型。看看https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/http/converter/HttpMessageConverter.html –

0

使用

@RequestMapping(value = "/url1", produces = "application/json") 

对JSON和它的更好的添加方式使用

@RequestMapping(value = "/url2", produces = "application/xml") 

用于XML输出