ResponseEntity和ResponseBody以及ResponseStatus區別
ResponseEntity和@ResponseBody以及@ResponseStatus區別
ResponseEntity 表示整個HTTP響應:狀態程式碼,標題和正文。因此,我們可以使用它來完全配置HTTP響應,它是一個物件,而@ResponseBody 和@ResponseStatus是註解,適合於簡單直接的場合。
@ResponseBody 一般與@Controller組合使用,用來返回JSON字串:
- @Controller
- @ResponseBody
而ResponseStatus一般與RestController組合使用:
- @RestController
- @ResponseStatus
@ResponseStatus無法設定標題,也無法設定HttpServletResponse或HttpHeaders引數,但是很簡單方便。
ResponseEntity讓你做更多的定製工作。
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雖然只是規定了返回的狀態,但是隻需要標註在方法上,簡單,而且狀態碼與返回型別分離,比較清晰。我們將上面返回物件列表的程式碼使用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提供方便功能 。
結論
@RestController + @ResponseStatus = @Controller +@ResponseBody