最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

一文詳解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) 的簡寫

返回驗(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 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)文章

  • idea快捷鍵生成getter和setter,有構(gòu)造參數(shù),無構(gòu)造參數(shù),重寫toString方式

    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配置國內(nèi)鏡像加速指南(最全最詳細(xì))

    在使用 Gradle 進(jìn)行 Java、Android 或其他 JVM 項(xiàng)目開發(fā)時,最令人頭疼的問題之一就是依賴下載速度慢,所以本文將提供最詳細(xì)最全面的 Gradle 配置國內(nèi)鏡像的指南,希望對大家有所幫助
    2025-08-08
  • java datetime數(shù)據(jù)類型去掉時分秒的案例詳解

    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)換器

    這篇文章主要介紹了jackson在springboot中的使用方式-自定義參數(shù)轉(zhuǎn)換器,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-10-10
  • 基于application和bootstrap的加載順序及區(qū)別說明

    基于application和bootstrap的加載順序及區(qū)別說明

    這篇文章主要介紹了application和bootstrap的加載順序及區(qū)別說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-07-07
  • 基于XML的Spring聲明事務(wù)控制

    基于XML的Spring聲明事務(wù)控制

    這篇文章主要為大家詳細(xì)介紹了基于XML的Spring聲明事務(wù)控制,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-07-07
  • springBoot接入阿里云oss的實(shí)現(xiàn)步驟

    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)

    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ū)別

    這篇文章主要介紹了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)換的全面指南

    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

最新評論

富阳市| 开远市| 迭部县| 霍山县| 镇康县| 鸡泽县| 英山县| 华亭县| 鄢陵县| 灵武市| 湘乡市| 改则县| 洱源县| 龙泉市| 江永县| 马鞍山市| 永平县| 米脂县| 贵德县| 五寨县| 溧阳市| 怀安县| 宝坻区| 喜德县| 龙岩市| 石景山区| 洪洞县| 文山县| 上杭县| 高清| 彝良县| 星子县| 高碑店市| 汝南县| 昌吉市| 尼玛县| 磐石市| 石棉县| 包头市| 鹿邑县| 富平县|