2014-01-31 31 views
1

我正在使用Spring @RESTController進行REST Web服務。而不是返回ModelAndView的對象我試圖在我的rest方法中返回ResponseEntity對象的對象。對於Strgin類型的響應,它正在UT當我建立ResponseEntity與jaxbObject獲得它給我的HTTP錯誤406
Spring 4 RestController - 如何使用ResponseEntity返回jaxb對象

@RestController 
@RequestMapping(value="/service") 
public class MyController { 
    public @ResponseBody ResponseEntity<String> getDashBoardData() throws JAXBException { 
    // Some Operation 
     return new ResponseEntity<String>(myStringXML, responseHeaders, HttpStatus.OK); 
    } 
} 

下面不工作

@RestController 
@RequestMapping(value="/service") 
public class MyController { 
    public @ResponseBody ResponseEntity<MyJaxbClass> getDashBoardData() throws JAXBException { 
    // Some Operation 
     return new ResponseEntity<MyJaxbClass>(MyJaxbClassObject, HttpStatus.OK); 
    } 
} 
+0

使用'@ RestController'時,您不需要隱含的'@ ResponseBody'。還要確保你已經正確配置了mvc的東西來編組jaxb對象。 –

+0

刪除@ResponseBody註釋不起作用。在這裏我有一個困惑,如果我返回一個ModelAndView比我可以指定JAXB的視圖解析器,但在這裏我返回ResponseEntity,你能給我一些指針,我怎麼可以爲ResponseEntity添加視圖解析器 –

+0

發佈一些相關的配置。 –

回答

3

@RestController註釋已經暗示@ResponseBody所有請求處理方法的註釋,這是它的目的之一(它可以避免將所有註釋放在那裏)。所以你可以/應該刪除它。

處理該方法的返回值是通過一個「HandlerMethodReturnValueHandler and the specific one which should handle this delegates to a HttpMessageConverter . It selects a specific HttpMessageConverter based on the requested/supported response types for the current request and the support response types from the HandlerMethodReturnValueHandler`完成。

一般情況下,當使用@EnableWebMvc<mvc:annotation-driven />時,應該自動設置一切。自動設置會檢測哪些庫可用(jaxb,json等)。

根據響應代碼(406),您可能在服務器端手動配置了錯誤的東西,或者客戶端不支持xml作爲響應類型。

+0

非常感謝,我沒有指定,這是問題所在。 –

相關問題