一文詳解Spring中ResponseEntity包裝器的使用
簡介
在 Spring 中,ResponseEntity 是 HTTP 響應(yīng)的包裝器。它允許自定義響應(yīng)的各個方面:
- HTTP 狀態(tài)碼
- 響應(yīng)主體
- HTTP 請求頭
使用 ResponseEntity 允許完全控制 HTTP 響應(yīng),并且它通常用于 RESTful Web 服務(wù)中從控制器方法返回響應(yīng)。
基本語法
ResponseEntity<T> response = new ResponseEntity<>(body, headers, status);
T:響應(yīng)主體的類型body:想要作為響應(yīng)主體發(fā)送的對象(如果不想返回主體,則可以為空)headers:想要包含的任何其他HTTP請求頭status:HTTP 狀態(tài)代碼(如HttpStatus.OK、HttpStatus.CREATED等)
示例用法
基本用法:返回簡單響應(yīng)
@RestController
@RequestMapping("/api/posts")
public class PostController {
@GetMapping("/{id}")
public ResponseEntity<Post> getPost(@PathVariable Long id) {
Post post = postService.findById(id);
if (post != null) {
return new ResponseEntity<>(post, HttpStatus.OK); // 200 OK
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND); // 404 Not Found
}
}
}
返回帶有請求頭的 ResponseEntity
@GetMapping("/custom-header")
public ResponseEntity<String> getWithCustomHeader() {
HttpHeaders headers = new HttpHeaders();
headers.add("Custom-Header", "CustomValue");
return new ResponseEntity<>("Hello with custom header!", headers, HttpStatus.OK);
}
返回具有創(chuàng)建狀態(tài)的 ResponseEntity
創(chuàng)建新資源時,通常希望返回 201 Created 狀態(tài)代碼
@PostMapping("/create")
public ResponseEntity<Post> createPost(@RequestBody Post post) {
Post createdPost = postService.save(post);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(createdPost.getId())
.toUri();
return ResponseEntity.created(location).body(createdPost);
}
返回沒有內(nèi)容的 ResponseEntity
當(dāng)成功處理一個請求但不需要返回任何內(nèi)容(例如,一個 DELETE 請求)時,可以使用 204 No Content
@DeleteMapping("/{id}")
public ResponseEntity<Void> deletePost(@PathVariable Long id) {
boolean isDeleted = postService.delete(id);
if (isDeleted) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT); // 204 No Content
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND); // 404 Not Found
}
}
使用帶有異常處理的 ResponseEntity
可以在全局異常處理程序或控制器中使用 ResponseEntity 來處理異常
@ExceptionHandler(PostNotFoundException.class)
public ResponseEntity<String> handlePostNotFound(PostNotFoundException ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
}
使用 Map 返回 ResponseEntity(例如,對于 JSON 響應(yīng))
@GetMapping("/user/{id}")
public ResponseEntity<Map<String, Object>> getUser(@PathVariable Long id) {
Map<String, Object> response = new HashMap<>();
User user = userService.findById(id);
if (user != null) {
response.put("status", "success");
response.put("data", user);
return new ResponseEntity<>(response, HttpStatus.OK);
} else {
response.put("status", "error");
response.put("message", "User not found");
return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
}
}
具有泛型類型的 ResponseEntity
@GetMapping("/posts/{id}")
public ResponseEntity<Post> getPostById(@PathVariable Long id) {
Post post = postService.findById(id);
if (post != null) {
return ResponseEntity.ok(post); // 200 OK with Post object as body
}
return ResponseEntity.status(HttpStatus.NOT_FOUND).build(); // 404 Not Found with no body
}
// ResponseEntity.ok(post) 是 new ResponseEntity<>(post, HttpStatus.OK) 的簡寫
返回驗證錯誤的 ResponseEntity
@PostMapping("/validate")
public ResponseEntity<Map<String, String>> validateUser(@RequestBody User user, BindingResult result) {
if (result.hasErrors()) {
Map<String, String> errorResponse = new HashMap<>();
result.getFieldErrors().forEach(error -> errorResponse.put(error.getField(), error.getDefaultMessage()));
return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST); // 400 Bad Request
}
userService.save(user);
return new ResponseEntity<>(HttpStatus.CREATED); // 201 Created
}
使用統(tǒng)一的響應(yīng)對象
1.定義統(tǒng)一響應(yīng)對象
public class ApiResponse<T> {
private String status;
private String message;
private T data;
private ErrorDetails error;
// Constructor for success response
public ApiResponse(String status, String message, T data) {
this.status = status;
this.message = message;
this.data = data;
}
// Constructor for error response
public ApiResponse(String status, String message, ErrorDetails error) {
this.status = status;
this.message = message;
this.error = error;
}
// Getters and setters
}
class ErrorDetails {
private String timestamp;
private int status;
private String error;
private String path;
// Getters and setters
}
2.在控制器方法中使用統(tǒng)一響應(yīng)
@GetMapping("/posts/{id}")
public ResponseEntity<ApiResponse<Post>> getPostById(@PathVariable Long id) {
Post post = postService.findById(id);
if (post != null) {
ApiResponse<Post> response = new ApiResponse<>(
"success",
"Post retrieved successfully",
post
);
return new ResponseEntity<>(response, HttpStatus.OK);
} else {
return getErrorResponse(HttpStatus.NOT_FOUND, "Post not found", "/api/posts/" + id);
}
}
private ResponseEntity<ApiResponse<Post>> getErrorResponse(HttpStatus status, String message, String path) {
ErrorDetails errorDetails = new ErrorDetails();
errorDetails.setTimestamp(LocalDateTime.now().toString());
errorDetails.setStatus(status.value());
errorDetails.setError(status.getReasonPhrase());
errorDetails.setPath(path);
ApiResponse<Post> response = new ApiResponse<>(
"error",
message,
errorDetails
);
return new ResponseEntity<>(response, status);
}
響應(yīng)數(shù)據(jù)結(jié)構(gòu)示例
1.Success
{
"status": "success",
"message": "Post retrieved successfully",
"data": {
"id": 1,
"title": "Hello World",
"content": "This is my first post"
}
}
2.Error
{
"status": "error",
"message": "Post not found",
"error": {
"timestamp": "2025-02-07T06:43:41.111+00:00",
"status": 404,
"error": "Not Found",
"path": "/api/posts/1"
}
}
3.使用 @ControllerAdvice 全局統(tǒng)一處理異常
@ControllerAdvice
public class GlobalExceptionHandler {
// Handle all exceptions
@ExceptionHandler(Exception.class)
public ResponseEntity<ApiResponse<Object>> handleGeneralException(Exception ex) {
ErrorDetails errorDetails = new ErrorDetails();
errorDetails.setTimestamp(LocalDateTime.now().toString());
errorDetails.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
errorDetails.setError("Internal Server Error");
errorDetails.setPath("/api/posts");
ApiResponse<Object> response = new ApiResponse<>("error", ex.getMessage(), errorDetails);
return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
常用的 HTTP 狀態(tài)碼
HttpStatus.OK:200 OKHttpStatus.CREATED:201 CreatedHttpStatus.NO_CONTENT:204 No ContentHttpStatus.BAD_REQUEST:400 Bad RequestHttpStatus.UNAUTHORIZED:401 UnauthorizedHttpStatus.FORBIDDEN:403 ForbiddenHttpStatus.NOT_FOUND:404 Not FoundHttpStatus.INTERNAL_SERVER_ERROR:500 Internal Server Error
到此這篇關(guān)于一文詳解Spring中ResponseEntity包裝器的使用的文章就介紹到這了,更多相關(guān)Spring ResponseEntity包裝器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Springboot3?ResponseEntity?完全使用案例
- SpringBoot中ResponseEntity的使用方法舉例詳解
- SpringBoot的ResponseEntity類返回給前端具體講解
- SpringBoot ResponseEntity標(biāo)識Http響應(yīng)方式
- 解決springboot responseentity<string>亂碼問題
- springmvc @ResponseStatus和ResponseEntity的使用
- SpringMVC使用ResponseEntity實現(xiàn)文件上傳下載
- 使用spring框架ResponseEntity實現(xiàn)文件下載
- Spring ResponseEntity的使用詳解
相關(guān)文章
springboot項目中PropertySource如何讀取yaml配置文件
這篇文章主要介紹了springboot項目中PropertySource如何讀取yaml配置文件問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-01-01
Spring動態(tài)多數(shù)據(jù)源配置實例Demo
本篇文章主要介紹了Spring動態(tài)多數(shù)據(jù)源配置實例Demo,具有一定的參考價值,有興趣的可以了解一下。2017-01-01
在Trae?IDE中創(chuàng)建Spring?AI項目的實現(xiàn)步驟
Trae是一個下一代AI代碼編輯器,具有智能代碼生成、自然語言交互、圖像輔助需求表達(dá)等功能,本文就來介紹一下Trae?IDE創(chuàng)建Spring?AI項目的實現(xiàn)步驟,感興趣的可以了解一下2025-08-08
Intellij IDEA 2018配置Java運(yùn)行環(huán)境的方法步驟
這篇文章主要介紹了Intellij IDEA 2018配置Java運(yùn)行環(huán)境的方法步驟,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09
Spring Cache擴(kuò)展功能實現(xiàn)過程解析
這篇文章主要介紹了Spring Cache擴(kuò)展功能實現(xiàn)解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-02-02
Spring解決循環(huán)依賴的方法及三級緩存機(jī)制實踐案例
Spring通過三級緩存解決單例Bean循環(huán)依賴,但無法處理構(gòu)造器、prototype作用域及@Async場景,建議使用setter注入、@Lazy注解和架構(gòu)優(yōu)化,遵循設(shè)計原則避免依賴問題,本文介紹Spring如何解決循環(huán)依賴:深入理解三級緩存機(jī)制,感興趣的朋友一起看看吧2025-09-09
Java設(shè)計模式之模板模式(Template模式)介紹
這篇文章主要介紹了Java設(shè)計模式之模板模式(Template模式)介紹,定義一個操作中算法的骨架,將一些步驟的執(zhí)行延遲到其子類中,需要的朋友可以參考下2015-03-03
swagger注解@ApiModelProperty失效情況的解決
這篇文章主要介紹了swagger注解@ApiModelProperty失效情況的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06

