在 Spring 框架中,ResponseEntity 是一个用于构建 HTTP 响应的强大工具类。它允许你完全控制 HTTP 响应的三个核心部分:状态码、响应头和响应体,是构建 REST API 时的关键组件。
一、核心作用
- 封装完整的 HTTP 响应
- 包含状态码(如
200 OK、404 Not Found) - 包含响应头(如
Content-Type、Cache-Control) - 包含响应体(返回给客户端的数据)
- 包含状态码(如
- 替代
@ResponseBody的更灵活方式@ResponseBody只能设置响应体,无法直接控制状态码和头信息ResponseEntity可以同时定制三者
二、关键属性与方法
1. 状态码(HTTP Status Code)
// 返回404 Not Found return ResponseEntity.notFound().build(); // 返回201 Created return ResponseEntity.status(HttpStatus.CREATED).body(newUser);
2. 响应头(HTTP Headers)
// 添加自定义头
HttpHeaders headers = new HttpHeaders();
headers.add("Location", "/users/" + userId);
return ResponseEntity.ok().headers(headers).body(user);
3. 响应体(Response Body)
// 返回JSON格式的用户对象 return ResponseEntity.ok(user); // 返回空响应(204 No Content) return ResponseEntity.noContent().build();
三、常见用法示例
1. 返回成功响应(200 OK)
@GetMapping("/users/{id}")
public ResponseEntity<User> getUser(@PathVariable Long id) {
User user = userService.findById(id);
return ResponseEntity.ok(user);
}
2. 返回创建成功(201 Created)
@PostMapping("/users")
public ResponseEntity<User> createUser(@RequestBody User user) {
User savedUser = userService.save(user);
return ResponseEntity
.created(URI.create("/users/" + savedUser.getId()))
.body(savedUser);
}
3. 返回错误响应(404 Not Found)
@GetMapping("/users/{id}")
public ResponseEntity<User> getUser(@PathVariable Long id) {
User user = userService.findById(id);
if (user == null) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(user);
}
4. 返回带自定义头的响应
@GetMapping("/download")
public ResponseEntity<Resource> downloadFile() {
Resource file = fileService.getFile();
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=file.txt")
.body(file);
}
四、与其他注解的对比
| 方式 | 控制状态码 | 控制响应头 | 控制响应体 | 适用场景 |
|---|---|---|---|---|
ResponseEntity | ✅ | ✅ | ✅ | 需完全自定义 HTTP 响应的场景 |
@ResponseBody | ❌ | ❌ | ✅ | 简单返回对象,使用默认状态码 |
@ResponseStatus | ✅ | ❌ | ✅ | 固定状态码,无需自定义响应头 |
@RestControllerAdvice | ✅ | ✅ | ✅ | 全局异常处理,统一响应格式 |
五、进阶技巧
1. 链式调用简化代码
return ResponseEntity
.status(HttpStatus.OK)
.header("Custom-Header", "value")
.contentType(MediaType.APPLICATION_JSON)
.body(user);
2. 泛型支持
// 明确指定响应体类型 ResponseEntity<User> response = ResponseEntity.ok(user);
3. 静态工厂方法
ResponseEntity.ok() // 200 OK ResponseEntity.created(uri) // 201 Created ResponseEntity.noContent() // 204 No Content ResponseEntity.badRequest() // 400 Bad Request ResponseEntity.notFound() // 404 Not Found
六、总结
ResponseEntity 是 Spring MVC 中构建 REST API 的核心工具,它让你能够:
- 精确控制 HTTP 响应的各个部分
- 实现标准化的错误处理
- 支持复杂的响应场景(如文件下载、自定义头)
过度使用 ResponseEntity
- 对于简单场景,优先使用
@ResponseBody+@ResponseStatus - 仅在需要复杂控制时使用
ResponseEntity