一文詳解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) 的簡寫
返回驗(yàn)證錯誤的 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實(shí)現(xiàn)文件上傳下載
- 使用spring框架ResponseEntity實(shí)現(xiàn)文件下載
- Spring ResponseEntity的使用詳解
相關(guān)文章
idea快捷鍵生成getter和setter,有構(gòu)造參數(shù),無構(gòu)造參數(shù),重寫toString方式
這篇文章主要介紹了java之idea快捷鍵生成getter和setter,有構(gòu)造參數(shù),無構(gòu)造參數(shù),重寫toString方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11
Gradle配置國內(nèi)鏡像加速指南(最全最詳細(xì))
在使用 Gradle 進(jìn)行 Java、Android 或其他 JVM 項(xiàng)目開發(fā)時,最令人頭疼的問題之一就是依賴下載速度慢,所以本文將提供最詳細(xì)最全面的 Gradle 配置國內(nèi)鏡像的指南,希望對大家有所幫助2025-08-08
java datetime數(shù)據(jù)類型去掉時分秒的案例詳解
在Java中,如果我們想要表示一個日期而不包括時間(時分秒),我們通常會使用java.time包中的LocalDate類,這篇文章主要介紹了java datetime數(shù)據(jù)類型去掉時分秒,需要的朋友可以參考下2024-06-06
jackson在springboot中的使用方式-自定義參數(shù)轉(zhuǎn)換器
這篇文章主要介紹了jackson在springboot中的使用方式-自定義參數(shù)轉(zhuǎn)換器,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-10-10
基于application和bootstrap的加載順序及區(qū)別說明
這篇文章主要介紹了application和bootstrap的加載順序及區(qū)別說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-07-07
springBoot接入阿里云oss的實(shí)現(xiàn)步驟
這篇文章主要介紹了springBoot接入阿里云oss的實(shí)現(xiàn)步驟,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
SpringBoot結(jié)合mockito測試實(shí)戰(zhàn)
與集成測試將系統(tǒng)作為一個整體測試不同,單元測試更應(yīng)該專注于某個類。所以當(dāng)被測試類與外部類有依賴的時候,尤其是與數(shù)據(jù)庫相關(guān)的這種費(fèi)時且有狀態(tài)的類,很難做單元測試。但好在可以通過“Mockito”這種仿真框架來模擬這些比較費(fèi)時的類,從而專注于測試某個類內(nèi)部的邏輯2022-11-11
Java注解@Conditional與@Profile的使用區(qū)別
這篇文章主要介紹了Java注解@Conditional與@Profile的使用區(qū)別,@Profile和@Conditional是Spring提供的兩種常用機(jī)制,它們可以根據(jù)不同的條件動態(tài)決定某些Bean是否加載,從而實(shí)現(xiàn)環(huán)境隔離、模塊選擇、特性開關(guān)等功能,需要的朋友可以參考下2025-05-05
Java實(shí)現(xiàn)字符串與基本數(shù)據(jù)類型轉(zhuǎn)換的全面指南
本文詳細(xì)介紹了Java中字符串與基本數(shù)據(jù)類型之間轉(zhuǎn)換的方法,包括將字符串轉(zhuǎn)換為基本數(shù)據(jù)類型,以及將基本數(shù)據(jù)類型轉(zhuǎn)換為字符串的各種技術(shù),有需要的小伙伴可以了解下2025-09-09

