Controller中返回數據總結(ResponseEntity,@ResponseBody,@ResponseStatus)
https://www.cnblogs.com/Jason-Xiang/p/10244075.html
在傳統的開發過程中,我們的控制CONTROLLER層通常需要轉向一個JSP視圖;但隨着WEB2.0相關技術的崛起,我們很多時候只需要返回數據即可,而不是一個JSP頁面。
- ResponseEntity:表示整個HTTP響應:狀態代碼,標題和正文。因此,我們可以使用它來完全配置HTTP響應,它是一個對象。
- @ResponseBody:返回json格式的結果
- @ResponseStatus:返回狀態
ResponseEntity
ResponseEntity是一種泛型類型。因此,我們可以使用任何類型作為響應主體:
@Controller public class XXXController{@GetMapping("/hello")
public ResponseEntity<String> hello() {
return new ResponseEntity<>("Hello World!", HttpStatus.OK);
}
這里字符串"Hello World!"作為字符串返回給REST端。
我們可以設置HTTP標頭:
@GetMapping("/customHeader") ResponseEntity<String> customHeader() { HttpHeaders headers = new HttpHeaders(); headers.add("Custom-Header", "foo");return new ResponseEntity<>(
"Custom header set", headers, HttpStatus.OK);
}
設置自定義標頭:
@GetMapping("/customHeader") ResponseEntity<String> customHeader() { return ResponseEntity.ok() .header("Custom-Header", "foo") .body("Custom header set")
如果將一個對象放入:
@GetMapping("/hello") public ResponseEntity<String> hello() { return new ResponseEntity<>(new User(‘jdon’), HttpStatus.OK); }
返回的是JSON字符串:
[ { ‘name’: 'jdon'}]
下面是返回對象的JSON列表:
public ResponseEntity<List<ProcessDef>> repositoryProcessDefinitionsGet() { return new ResponseEntity<>(processDefRepo.findAll(), HttpStatus.FOUND); }
以上是通過ResponseEntity這個對象在代碼中靈活操控響應,但是在一般情況下我們只是想返回一個帶有數據的正常響應,那么只要使用@注解即可
@ResponseBody
在類級別使用@Controller標注情況下, @ResponseBody注解告訴返回的對象將自動序列化為JSON,並通過回控制器的HttpResponse對象。
@Controller public class XXXController{@ResponseBody
public User postResponseController(@RequestBody LoginForm loginForm) {
return new User("Thanks For Posting!!!");
}
將返回客戶端JSON字符串:
[ { ‘name’: Thanks For Posting!!!"}]
在@RestController注解了類的情況下,我們就不需要再使用@ResponseBody了。
@ResponseStatus
ResponseStatus雖然只是規定了返回的狀態,但是只需要標注在方法上,簡單,而且狀態碼與返回類型分離,比較清晰。我們將上面返回對象列表的代碼使用ResponseStatus改寫如下,注意類級別@RestController:
@RestController public class XXXController{@ResponseStatus(HttpStatus.FOUND)
public User postResponseController() {
return new User("Thanks For Posting!!!");
}
這也會返回客戶端JSON字符串:
[ { ‘name’: Thanks For Posting!!!"}]
這樣的代碼更加專注於業務。
直接操控響應
Spring還允許我們直接訪問javax.servlet.http.HttpServletResponse對象; 我們只需要將它聲明為方法參數:
@GetMapping("/manual") public void manual(HttpServletResponse response) throws IOException { response.setHeader("Custom-Header", "foo"); response.setStatus(200); response.getWriter().println("Hello World!"); }
由於Spring在底層實現之上提供了抽象和附加功能,因此如果以這種方式直接操縱響應,會失去很多Spring提供方便功能。
參考:
SPRING MVC3.2案例講解--SPRING MVC3的@ResponseBody和ResponseEntity
ResponseEntity和@ResponseBody以及@ResponseStatus區別