ResponseEntity<T> cho phép kiểm soát hoàn toàn HTTP response: status code, headers, body.
java
@RestController
@RequestMapping("/api/users")
class UserController {
@PostMapping
ResponseEntity<User> create(@RequestBody @Valid CreateUserRequest req) {
User user = userService.create(req);
URI location = URI.create("/api/users/" + user.getId());
return ResponseEntity
.created(location) // 201 Created + Location header
.body(user);
}
@DeleteMapping("/{id}")
ResponseEntity<Void> delete(@PathVariable Long id) {
userService.delete(id);
return ResponseEntity.noContent().build(); // 204 No Content
}
@GetMapping("/{id}")
ResponseEntity<User> get(@PathVariable Long id) {
return userService.findById(id)
.map(ResponseEntity::ok) // 200 OK
.orElse(ResponseEntity.notFound().build()); // 404 Not Found
}
@PutMapping("/{id}")
ResponseEntity<User> update(
@PathVariable Long id,
@RequestBody @Valid UpdateUserRequest req
) {
User updated = userService.update(id, req);
return ResponseEntity.ok()
.header("X-Updated-At", Instant.now().toString())
.body(updated);
}
}Khi trả trực tiếp object: Spring dùng 200 OK mặc định.
Dùng ResponseEntity khi cần: status khác 200, custom header, hoặc response body có thể null.
ResponseEntity<T> gives you full control over the HTTP response: status code, headers, and body.
java
@RestController
@RequestMapping("/api/users")
class UserController {
@PostMapping
ResponseEntity<User> create(@RequestBody @Valid CreateUserRequest req) {
User user = userService.create(req);
URI location = URI.create("/api/users/" + user.getId());
return ResponseEntity
.created(location) // 201 Created + Location header
.body(user);
}
@DeleteMapping("/{id}")
ResponseEntity<Void> delete(@PathVariable Long id) {
userService.delete(id);
return ResponseEntity.noContent().build(); // 204 No Content
}
@GetMapping("/{id}")
ResponseEntity<User> get(@PathVariable Long id) {
return userService.findById(id)
.map(ResponseEntity::ok) // 200 OK
.orElse(ResponseEntity.notFound().build()); // 404 Not Found
}
@PutMapping("/{id}")
ResponseEntity<User> update(
@PathVariable Long id,
@RequestBody @Valid UpdateUserRequest req
) {
User updated = userService.update(id, req);
return ResponseEntity.ok()
.header("X-Updated-At", Instant.now().toString())
.body(updated);
}
}When returning an object directly: Spring defaults to 200 OK.
Use ResponseEntity when you need: a non-200 status, custom headers, or a potentially null body.