使用Spring ResponseEntity處理http響應
簡介
使用Spring時,達到同一目的通常有很多方法,對處理http響應也是一樣。本文我們將學習如何通過ResponseEntity設置http相應內容、狀態以及頭信息。
ResponseEntity
ResponspEntity標識整個http相應:狀態碼、頭部信息以及相應體內容。因此我們可以使用其對http響應實現完整配置。
如果需要使用ResponspEntity,必須在請求點返回,通常在spring rest中實現。
ResponspEntity是通用類型,因此可以使用任意類型作為響應體:
@GetMapping("/hello") public ResponseEntity<String> hello(){ return new ResponseEntity<>("hello word!", HttpStatus.OK); }
可以通過編程方式指明響應狀態,所以根據不同場景返回不同狀態:
@GetMapping("/age") public ResponseEntity<String> age(@RequestParam("yearOfBirth")int yearOfBirth){ if(isInFuture(yearOfBirth)){ return new ResponseEntity<>("",HttpStatus.BAD_REQUEST); } return new ResponseEntity<>("Your age is"+calculateAge(yearOfBirth),HttpStatus.OK); }
另外還可以設置http響應頭:
@GetMapping("/customHeader") public ResponseEntity<String> customHeader(){ HttpHeaders headers=new HttpHeaders(); headers.add("Custom-Header","foo"); return new ResponseEntity<>("hello word!", headers,HttpStatus.OK); }
而且,ResponseEntity提供了兩個內嵌的構建器接口:HeadersBuilder和其子接口BodyBuilder。因此我們能通過ResponseEntity的靜態方法直接訪問。
大多數常用的http響應碼,可以通過下面static方法:
BodyBuilder accepted(); BodyBuilder badRequest(); BodyBuilder created(java.net.URI location); HeadersBuilder<?> noContent(); HeadersBuilder<?> notFound(); BodyBuilder ok();
另外,可以使用BodyBuilder status(HTTPStatus status)和BodyBuilder status(int status)方法設置http狀態。使用ResponseEntity BodyBuilder.body(T body)設置http響應體:
@GetMapping("all") public ResponseEntity<List> All(){ return ResponseEntity.ok().body(userService.findAll()); }
盡管ResponseEntity非常強大,但不應該過度使用。在一些簡單情況下,還有其他方法能滿足我們的需求,使代碼更整潔。
代替方法
@ResponseBody
典型spring mvc應用,請求點通常返回html頁面。有時我們僅需要實際數據,如使用ajax請求,這時我們能通過@ResponseBody注解標記請求處理方法,審批人能夠處理方法結果值作為http響應體。
@ResponsoStatus
當請求點成功返回,spring提供http 200(ok)響應。如果請求點拋出異常,spring查找異常處理器,由其返回相應的http狀態碼。對這些方法增加@ResponseStatus注解,spring會返回自定義http狀態碼。
如果對你有用,記得點贊收藏,關注一波不迷路