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> findAll(@RequestParam(name = "admin", required = false) String admin, @RequestParam(name = "page", defaultValue = "1") Integer page, @RequestParam(name = "rows", defaultValue = "10") Integer rows) {
        PageResult 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));
    }

你可能感兴趣的:(Java,java,spring)