2014-09-10 63 views
4

我已將我的休息服務的異常處理集中到一個整潔的ControllerAdvice中。我希望我的controlleradvice在處理異常時總是生成JSON

我正在返回定期傳輸對象,希望我的酷映射傑克遜轉換器將它轉換成JSON爲最終客戶端。

現在就是這樣的事情。如果我沒有將accept-header設置爲「Application/JSON」,我不會獲得轉換後的JSON,而是在我的測試中看到由Jetty生成的一些默認HTML。我不得不承認我不知道爲什麼,但我想這是一些默認的Spring解析器生效。

這讓我思考。呼叫我的其餘URL的客戶應該知道我返回JSON,所以我希望我的服務始終返回json。

有沒有辦法配置ReqeustMappingHandlerAdapter來始終生成JSON?

我目前的配置:

<beans:bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> 
    <beans:property name="messageConverters"> 
     <beans:list> 
      <beans:ref bean="jsonConverter"/> 
     </beans:list> 
    </beans:property> 
</beans:bean> 

<!-- Instantiation of the converter in order to configure it --> 
<beans:bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> 
    <!--beans:property name="supportedMediaTypes" value="application/json"/--> 
</beans:bean> 
+0

你可以發表你的方法異常處理程序定義是什麼? – 2014-09-10 20:36:06

+0

我只有一個@controlleradvice類,就像這個例子http://www.petrikainulainen.net/programming/spring-framework/spring-from-the-trenches-adding-validation-to-a-rest-api/ – Mathias 2014-09-10 20:41:19

+0

你的方法是否有@ResponseBody註解? – 2014-09-10 21:15:51

回答

1

我不知道這是否回答你的問題,但你可以在Spring配置設置的默認內容類型以JSON(默認爲HTML,而不在Spring MVC中接受頭文件)。這裏有一個例子:

<bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean"> 
    <property name="defaultContentType" value="application/json" /> 
</bean> 

<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager" /> 

來源:

http://spring.io/blog/2013/05/11/content-negotiation-using-spring-mvc

+0

謝謝。這不是一個壞主意,但不會爲我的應用程序工作,因爲我有JSON和Html客戶端。 – Mathias 2014-11-07 08:11:29

相關問題