假設我有一個控制器,供應GET
請求,並返回豆被序列化到JSON並且還提供了IllegalArgumentException
異常處理程序可以在服務方式籌集:如何更改異常處理程序的內容類型
@RequestMapping(value = "/meta/{itemId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public MetaInformation getMetaInformation(@PathVariable int itemId) {
return myService.getMetaInformation(itemId);
}
@ExceptionHandler(IllegalArgumentException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ResponseBody
public String handleIllegalArgumentException(IllegalArgumentException ex) {
return ExceptionUtils.getStackTrace(ex);
}
信息轉換器有:
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
<bean class="org.springframework.http.converter.StringHttpMessageConverter" />
</mvc:message-converters>
</mvc:annotation-driven>
現在,當我要求給定的URL在瀏覽器中我看到了正確的JSON回覆。但是,如果引發異常,字符串化的異常也會轉換爲JSON,但是我希望它能夠被StringHttpMessageConverter
(導致text/plain
mime類型)處理。我怎麼去呢?
爲了使畫面更完整的(複雜),假設我也有以下處理:
@RequestMapping(value = "/version", method = RequestMethod.GET)
@ResponseBody
public String getApplicationVersion() {
return "1.0.12";
}
這個處理器允許返回串,既MappingJackson2HttpMessageConverter
和StringHttpMessageConverter
根據傳入Accept-type
被序列化客戶。返回類型和值應爲:
+----+---------------------+-----------------------+------------------+-------------------------------------+ | NN | URL | Accept-type | Content-type | Message converter | | | | request header | response header | | +----+---------------------+-----------------------+------------------+-------------------------------------+ | 1. | /version | text/html; */* | text/plain | StringHttpMessageConverter | | 2. | /version | application/json; */* | application/json | MappingJackson2HttpMessageConverter | | 3. | /meta/1 | text/html; */* | application/json | MappingJackson2HttpMessageConverter | | 4. | /meta/1 | application/json; */* | application/json | MappingJackson2HttpMessageConverter | | 5. | /meta/0 (exception) | text/html; */* | text/plain | StringHttpMessageConverter | | 6. | /meta/0 (exception) | application/json; */* | text/plain | StringHttpMessageConverter | +----+---------------------+-----------------------+------------------+-------------------------------------+
聽起來不錯。但是如何處理場景(3,4)? –
感謝提供'ResponseEntity'的提示!怎麼樣爲'StringHttpMessageConverter'設置'supportedMediaTypes'屬性(見[我的答案](http://stackoverflow.com/a/12979543/267197))?也可能是一個解決方案。 –
我剛剛用'ResponseEntity'檢查了你的解決方案:它不起作用。內容類型被消息轉換器覆蓋,並且通過相交'Accept-type'和轉換器'supportedMediaTypes'選擇消息轉換器(粗略算法)。 –