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请求新增一条记录时,有返回值

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));
    }

你可能感兴趣的:(ResponseEntity的返回值用法)