统一结果返回 ResponseEntity

统一结果返回 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);
    }
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值