Spring中的ResponseEntity使用和理解


HttpEntity 定義了 header,body屬性,重寫Object toString
ResponseEntity 定義了status屬性 , 繼承HttpEntity ,然后再增強;
內部構建BodyBuilder HeaderBuilder接口, 大多內部方法返回此接口,實現鏈式賦值.
例:ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult)

封裝狀態碼和返回數據

也可以用來封裝返回的具體數據,
ResponseEntity<有具體泛型> ,同樣可以用來接收ResponseEntity.ok
例如,我想達到的效果是 : 如果service層執行出錯,返回錯誤結果,如果正常,只返回200.
案例中,自行封裝了ErrorResult類 , 包含errorCode errMsg.

//只返回200
ResponseEntity<ErrorResult> response = ResponseEntity.ok(null);

//返回具體錯誤
ErrorResult.builder().errCode("002").errMessage("驗證碼發送失敗").build();
ResponseEntity<ErrorResult> response = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);

構造方法很多,靈活使用

return new ResponseEntity<>("Hello World!", HttpStatus.OK)
//包含自定義響應頭的
	HttpHeaders headers = new HttpHeaders();
    headers.add("Custom-Header", "foo");

    return new ResponseEntity<>(
      "Custom header set", headers, HttpStatus.OK);
	  
//鏈式header,body賦值
ResponseEntity<String> customHeader() {
    return ResponseEntity.ok()
        .header("Custom-Header", "foo")
        .body("Custom header set");
}

替代方法 :
@ResponseBody 使用Controller返回值作為返回值,
@ResponseStatus 由Spring返回相應的http狀態碼 200 | 其他
不過使用不如 ResponseEntity 靈活度高

小注意點

enum HttpStatus 內置狀態碼枚舉
Header只接收Map<String,String> / null

參考:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM