一文詳解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)文章希望大家以后多多支持腳本之家!
相關(guān)文章
關(guān)于使用MyBatis簡化JDBC開發(fā)和解決SQL語句警告的問題
這篇文章主要介紹了關(guān)于使用MyBatis簡化JDBC開發(fā)和解決SQL語句警告的問題,如果idea和數(shù)據(jù)庫沒有建立鏈接,idea不識別表的信息,就會出現(xiàn)SQL語句的警告,需要的朋友可以參考下2023-05-05Java11?中基于嵌套關(guān)系的訪問控制優(yōu)化問題
在?Java?語言中,類和接口可以相互嵌套,這種組合之間可以不受限制的彼此訪問,包括訪問彼此的構(gòu)造函數(shù)、字段、方法,接下來通過本文給大家介紹Java11中基于嵌套關(guān)系的訪問控制優(yōu)化問題,感興趣的朋友一起看看吧2022-01-01SpringBoot 如何使用RestTemplate發(fā)送Post請求
這篇文章主要介紹了SpringBoot 如何使用RestTemplate發(fā)送Post請求的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08Java中數(shù)組與集合的相互轉(zhuǎn)換實現(xiàn)解析
這篇文章主要介紹了Java中數(shù)組與集合的相互轉(zhuǎn)換實現(xiàn)解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-08-08SpringCloud實現(xiàn)基于RabbitMQ消息隊列的詳細(xì)步驟
在Spring Cloud框架中,我們可以利用RabbitMQ實現(xiàn)強(qiáng)大而可靠的消息隊列系統(tǒng),本篇將詳細(xì)介紹如何在Spring Cloud項目中集成RabbitMQ,并創(chuàng)建一個簡單的消息隊列,感興趣的朋友一起看看吧2024-03-03