在傳統的開發過程中,我們的控制CONTROLL層通常需要轉向一個JSP視圖;但隨著WEB2.0相關技術的崛起,我們很多時候只需要返回數據即可,而不是一個JSP頁面。
?
SPRING MVC3的@ResponseBody使Controller直接返回數據,而不是直接指向具體的視圖;同時通過
MessageConverter和produces(如produces="text/plain;charset=UTF-8")可以返回各種格式的數據(XML,json,RSS,TEXT,字節流等),本章只介紹最簡單的使用;
見代碼:
@ResponseBody可以直接返回結果,
而ResponseEntity?可以定義返回的HttpHeaders和HttpStatus,見文章最后的兩張圖
?
[java]?view plaincopy
@RequestMapping(value="/response",?method=RequestMethod.GET)??public?class?ResponseController?{????????@RequestMapping("/annotation")??????public?@ResponseBody?String?responseBody()?{??????????return?"The?String?ResponseBody";??????}??????????@RequestMapping("/charset/accept")??????public?@ResponseBody?String?responseAcceptHeaderCharset()?{??????????return?"\u3053\u3093\u306b\u3061\u306f\u4e16\u754c\uff01?(\"Hello?world!\"?in?Japanese)";??????}????????@RequestMapping(value="/charset/produce",?produces="text/plain;charset=UTF-8")??????public?@ResponseBody?String?responseProducesConditionCharset()?{??????????return?"\u3053\u3093\u306b\u3061\u306f\u4e16\u754c\uff01?(\"Hello?world!\"?in?Japanese)";??????}????????@RequestMapping("/entity/status")??????public?ResponseEntity<String>?responseEntityStatusCode()?{??????????return?new?ResponseEntity<String>("The?String?ResponseBody?with?custom?status?code?(403?Forbidden)",??????????????????HttpStatus.FORBIDDEN);??????}????????@RequestMapping("/entity/headers")??????public?ResponseEntity<String>?responseEntityCustomHeaders()?{??????????HttpHeaders?headers?=?new?HttpHeaders();??????????headers.setContentType(MediaType.TEXT_PLAIN);??????????return?new?ResponseEntity<String>("The?String?ResponseBody?with?custom?header?Content-Type=text/plain",??????????????????headers,?HttpStatus.OK);??????}????}?? ?
?
?
轉載于:https://www.cnblogs.com/may-25/p/5485948.html
總結
以上是生活随笔為你收集整理的[转发]SPRING MVC3.2案例讲解--SPRING MVC3的@ResponseBody和ResponseEntity的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。