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