在傳統的開發過程當中,咱們的控制CONTROLL層一般須要轉向一個JSP視圖;但隨着WEB2.0相關技術的崛起,咱們不少時候只須要返回數據便可,而不是一個JSP頁面。java
SPRING MVC3的@ResponseBody使Controller直接返回數據,而不是直接指向具體的視圖;同時經過json
MessageConverter和produces(如produces="text/plain;charset=UTF-8")能夠返回各類格式的數據(XML,json,RSS,TEXT,字節流等),本章只介紹最簡單的使用;
見代碼:app
@ResponseBody能夠直接返回結果,spa
而ResponseEntity 能夠定義返回的HttpHeaders和HttpStatus,見文章最後的兩張圖
- @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);
- }
-
- }