统一结果返回 ResponseEntity
在正规的严格的企业的前后端系统开发中,返回严谨的状态码很有必要
平常大家为了统一格式返回,或许会自己封装一个ResultUtils,然后自定义ResultCode枚举类来返回,这样有些麻烦;
我们可以使用SpringMVC为我们封装的ResponseEntity对象来自定义状态码
源码:
public class ResponseEntity<T> extends HttpEntity<T> {
private final Object status;
public ResponseEntity(HttpStatus status) {
this((Object)null, (MultiValueMap)null, (HttpStatus)status);
}
public ResponseEntity(@Nullable T body, HttpStatus status) {
this(body, (MultiValueMap)null, (HttpStatus)status);
}
public ResponseEntity(MultiValueMap<String, String> headers, HttpStatus status) {
this((Object)null, headers, (HttpStatus)status);
}
public ResponseEntity(@Nullable T body, @Nullable MultiValueMap<String, String> headers, HttpStatus status) {
super(body, headers);
Assert.notNull(status, "HttpStatus must not be null");
this.status = status;
}
private ResponseEntity(@Nullable T body, @Nullable MultiValueMap<String, String> headers, Object status) {
super(body, headers);
Assert.notNull(status, "HttpStatus must not be null");
this.status = status;
}
@param body: the entity body
ResponseEntity需要一个泛型T,代表我们需要传入的数据对象
@param headers : the entity headers
我们可以new MultiValueMap<String, String> headers,设置响应头信息
@param status: the status code
我们可以使用HttpStatus,也可以自己定义状态码(Object)
HttpStatus status是一个包含了各种响应状态码的枚举类
// 201:创建成功 Created
// 203 :没有认证 NON_AUTHORITATIVE_INFORMATION
// 204: 成功没有返回值 No-content 一般是delete,update时使用
.....
例子:
@GetMapping("/categories")
public ResponseEntity<List<Category>> getCategoryList(String token){
return new ResponseEntity<>(categoryService.queryAll(), HttpStatus.OK);
}
@PostMapping("/categories")
public ResponseEntity<Category> AddCategory(String token, @RequestBody Category category){
return new ResponseEntity<>(categoryService.insert(category),HttpStatus.CREATED);
}