2016-04-14 47 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輸出