ResponseEntity的返回值用法

我们在使用ResponseEntity时,更多的是为了设置不同的HttpResponse Code,如果你的系统偏好是通过Response Body中的Code来判断API状态即几乎所有API的HttpResponse Code=200,那么完全可以不使用ResponseEntity作为返回数据类型,只需要去返回Response Body,通过Body中开发者自定义的Code给API设置状态。

例如  Response Body
{
    code: 200,
    ErrorMessage: "error message",
    data: {}
}

Get请求时

return ResponseEntity.ok();
例如:
@GetMapping({"findAll"})
    public ResponseEntity<PageResult<User>> findAll(@RequestParam(name = "admin", required = false) String admin, @RequestParam(name = "page", defaultValue = "1") Integer page, @RequestParam(name = "rows", defaultValue = "10") Integer rows) {
        PageResult<User> userPageResult = this.userService.findAll(admin, page, rows);
        return ResponseEntity.ok(userPageResult);
    }

Post请求新增一条记录时,有返回值

//body()里存放的是返回的内容
return ResponseEntity.status(HttpStatus.CREATE).body();
例如:
@PostMapping("save")
   public ResponseEntity save(@RequestBody User user) throws Exception {
        return ResponseEntity.status(HttpStatus.CREATED).body(this.userService.save(user));
   }

Post请求新增一条记录时,无返回值

return new ResponseEntity(HttpStatus.CREATED);

Delete删除请求,无返回

return new ResponseEntity(HttpStatus.NO_CONTENT);
例如:
@DeleteMapping({"delete"})
    public ResponseEntity delete(@RequestParam(name = "ids") Integer[] ids) {
        return ResponseEntity.ok(this.userService.delete(ids));
    }

Put更新请求,无返回值

ResponseEntity.noContent().build();
例如:
@PutMapping({"update"})
    public ResponseEntity update(@RequestBody User user) throws Exception {
        return ResponseEntity.ok(this.userService.update(user));
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值