欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

一文詳解Spring中ResponseEntity包裝器的使用

 更新時間:2025年02月11日 08:21:46   作者:唐青楓  
在?Spring?中,ResponseEntity?是?HTTP?響應(yīng)的包裝器,這篇文章主要為大家詳細(xì)介紹了ResponseEntity包裝器的使用,感興趣的可以了解一下

簡介

Spring 中,ResponseEntityHTTP 響應(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 OK
  • HttpStatus.CREATED:201 Created
  • HttpStatus.NO_CONTENT:204 No Content
  • HttpStatus.BAD_REQUEST:400 Bad Request
  • HttpStatus.UNAUTHORIZED:401 Unauthorized
  • HttpStatus.FORBIDDEN:403 Forbidden
  • HttpStatus.NOT_FOUND:404 Not Found
  • HttpStatus.INTERNAL_SERVER_ERROR:500 Internal Server Error

到此這篇關(guān)于一文詳解Spring中ResponseEntity包裝器的使用的文章就介紹到這了,更多相關(guān)Spring ResponseEntity包裝器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 使用eclipse創(chuàng)建java項目的方法

    使用eclipse創(chuàng)建java項目的方法

    這篇文章主要為大家詳細(xì)介紹了使用eclipse創(chuàng)建java項目的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-04-04
  • SpringBoot項目修改訪問端口和訪問路徑的方法

    SpringBoot項目修改訪問端口和訪問路徑的方法

    這篇文章主要介紹了SpringBoot項目修改訪問端口和訪問路徑的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-12-12
  • 關(guān)于使用MyBatis簡化JDBC開發(fā)和解決SQL語句警告的問題

    關(guān)于使用MyBatis簡化JDBC開發(fā)和解決SQL語句警告的問題

    這篇文章主要介紹了關(guān)于使用MyBatis簡化JDBC開發(fā)和解決SQL語句警告的問題,如果idea和數(shù)據(jù)庫沒有建立鏈接,idea不識別表的信息,就會出現(xiàn)SQL語句的警告,需要的朋友可以參考下
    2023-05-05
  • Java11?中基于嵌套關(guān)系的訪問控制優(yōu)化問題

    Java11?中基于嵌套關(guān)系的訪問控制優(yōu)化問題

    在?Java?語言中,類和接口可以相互嵌套,這種組合之間可以不受限制的彼此訪問,包括訪問彼此的構(gòu)造函數(shù)、字段、方法,接下來通過本文給大家介紹Java11中基于嵌套關(guān)系的訪問控制優(yōu)化問題,感興趣的朋友一起看看吧
    2022-01-01
  • java 單例模式容易忽略的細(xì)節(jié)

    java 單例模式容易忽略的細(xì)節(jié)

    這篇文章主要介紹了java 單例模式容易忽略的細(xì)節(jié),幫助大家更好的理解和使用java 單例模式,感興趣的朋友可以了解下
    2020-12-12
  • SpringBoot 如何使用RestTemplate發(fā)送Post請求

    SpringBoot 如何使用RestTemplate發(fā)送Post請求

    這篇文章主要介紹了SpringBoot 如何使用RestTemplate發(fā)送Post請求的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-08-08
  • 分享一個你不知道的Java異常實現(xiàn)的缺陷

    分享一個你不知道的Java異常實現(xiàn)的缺陷

    Java中一個大家熟知的知識點就是異常捕獲,try...catch...finally組合,但是很多人不知道這里面有一個關(guān)于Java的缺陷,或者說是異常實現(xiàn)的一點不足之處。本文就通過一個很簡單的實驗給大家演示下效果玩玩兒,希望大家能覺得有趣
    2022-12-12
  • Java中數(shù)組與集合的相互轉(zhuǎn)換實現(xiàn)解析

    Java中數(shù)組與集合的相互轉(zhuǎn)換實現(xiàn)解析

    這篇文章主要介紹了Java中數(shù)組與集合的相互轉(zhuǎn)換實現(xiàn)解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-08-08
  • SpringCloud實現(xiàn)基于RabbitMQ消息隊列的詳細(xì)步驟

    SpringCloud實現(xiàn)基于RabbitMQ消息隊列的詳細(xì)步驟

    在Spring Cloud框架中,我們可以利用RabbitMQ實現(xiàn)強(qiáng)大而可靠的消息隊列系統(tǒng),本篇將詳細(xì)介紹如何在Spring Cloud項目中集成RabbitMQ,并創(chuàng)建一個簡單的消息隊列,感興趣的朋友一起看看吧
    2024-03-03
  • 為什么JDK8中HashMap依然會死循環(huán)

    為什么JDK8中HashMap依然會死循環(huán)

    這篇文章主要介紹了為什么JDK8中HashMap依然會死循環(huán),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-09-09

最新評論