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

SpringBoot統(tǒng)一數(shù)據(jù)返回的幾種方式

 更新時間:2024年07月19日 09:35:55   作者:碼農(nóng)阿豪@新空間代碼工作室  
在Web應(yīng)用程序開發(fā)中,統(tǒng)一數(shù)據(jù)返回格式對于前后端分離項目尤為重要,本文就來介紹一下SpringBoot統(tǒng)一數(shù)據(jù)返回的幾種方式,具有一定的參考價值,感興趣的可以了解一下

在Web應(yīng)用程序開發(fā)中,統(tǒng)一數(shù)據(jù)返回格式對于前后端分離項目尤為重要。通過統(tǒng)一的數(shù)據(jù)返回格式,可以大大簡化前端數(shù)據(jù)解析的復(fù)雜度,提高代碼的可維護(hù)性和一致性。本文將介紹如何在Spring Boot項目中實現(xiàn)統(tǒng)一的數(shù)據(jù)返回格式。

一、概念

統(tǒng)一數(shù)據(jù)返回指的是將所有接口的返回數(shù)據(jù)進(jìn)行統(tǒng)一封裝,使用一致的格式返回給前端。例如,可以定義一個標(biāo)準(zhǔn)的響應(yīng)格式,包括狀態(tài)碼、消息、數(shù)據(jù)等信息:

{
    "code": 200,
    "message": "Success",
    "data": { ... }
}

通過這種方式,前端開發(fā)人員只需處理一種響應(yīng)格式,減少解析錯誤和代碼冗余。

二、實現(xiàn)統(tǒng)一數(shù)據(jù)返回

為了實現(xiàn)統(tǒng)一的數(shù)據(jù)返回格式,我們可以使用Spring Boot的ResponseBodyAdvice接口,該接口可以在響應(yīng)返回之前對響應(yīng)體進(jìn)行處理。

2.1 重寫responseAdvice方法

首先,我們需要創(chuàng)建一個類,實現(xiàn)ResponseBodyAdvice接口,并重寫其中的方法:

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice
public class GlobalResponseAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, 
                                  Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof ResponseEntity) {
            return body;
        }
        return new ApiResponse(200, "Success", body);
    }
}

在上面的代碼中,supports方法用于判斷哪些接口的返回值需要處理,這里返回true表示處理所有接口的返回值。beforeBodyWrite方法則是在響應(yīng)體寫入之前進(jìn)行處理,將返回的數(shù)據(jù)封裝為統(tǒng)一格式的ApiResponse對象。

2.2 實現(xiàn)ApiResponse類

創(chuàng)建ApiResponse類,用于定義統(tǒng)一的響應(yīng)格式:

public class ApiResponse<T> {

    private int code;
    private String message;
    private T data;

    public ApiResponse(int code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    // Getters and Setters
}

三、特殊類型-String的處理

由于Spring在處理String類型的返回值時,會直接將其寫入響應(yīng)體,而不會經(jīng)過HttpMessageConverter,因此我們需要對String類型進(jìn)行特殊處理:

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice
public class GlobalResponseAdvice implements ResponseBodyAdvice<Object> {

    private final ObjectMapper objectMapper;

    public GlobalResponseAdvice(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, 
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType, 
                                  ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof String) {
            try {
                return objectMapper.writeValueAsString(new ApiResponse<>(200, "Success", body));
            } catch (Exception e) {
                throw new RuntimeException("Failed to write response as String", e);
            }
        }
        if (body instanceof ResponseEntity) {
            return body;
        }
        return new ApiResponse<>(200, "Success", body);
    }
}

在上面的代碼中,我們使用ObjectMapperApiResponse對象轉(zhuǎn)換為String,確保String類型的返回值也能統(tǒng)一為標(biāo)準(zhǔn)格式。

四、全部代碼

// ApiResponse.java
public class ApiResponse<T> {

    private int code;
    private String message;
    private T data;

    public ApiResponse(int code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    // Getters and Setters
}

// GlobalResponseAdvice.java
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice
public class GlobalResponseAdvice implements ResponseBodyAdvice<Object> {

    private final ObjectMapper objectMapper;

    public GlobalResponseAdvice(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, 
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType, 
                                  ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof String) {
            try {
                return objectMapper.writeValueAsString(new ApiResponse<>(200, "Success", body));
            } catch (Exception e) {
                throw new RuntimeException("Failed to write response as String", e);
            }
        }
        if (body instanceof ResponseEntity) {
            return body;
        }
        return new ApiResponse<>(200, "Success", body);
    }
}

通過上述代碼,我們可以實現(xiàn)Spring Boot項目中統(tǒng)一的數(shù)據(jù)返回格式。無論返回的數(shù)據(jù)類型如何,都可以通過統(tǒng)一封裝后的格式返回給前端,極大地提高了代碼的可維護(hù)性和前后端的開發(fā)效率。

到此這篇關(guān)于SpringBoot統(tǒng)一數(shù)據(jù)返回的幾種方式的文章就介紹到這了,更多相關(guān)SpringBoot統(tǒng)一數(shù)據(jù)返回內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 啟用設(shè)置org.slf4j.Logger打印并輸出日志方式

    啟用設(shè)置org.slf4j.Logger打印并輸出日志方式

    這篇文章主要介紹了啟用設(shè)置org.slf4j.Logger打印并輸出日志方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-11-11
  • Java 裝箱與拆箱詳解及實例代碼

    Java 裝箱與拆箱詳解及實例代碼

    這篇文章主要介紹了Java 裝箱與拆箱詳解及實例代碼的相關(guān)資料,這里對java 的裝箱及拆箱進(jìn)行了基本概念詳解及簡單使用,需要的朋友可以參考下
    2017-01-01
  • SpringBoot整合Mybatis-Plus+Druid實現(xiàn)多數(shù)據(jù)源配置功能

    SpringBoot整合Mybatis-Plus+Druid實現(xiàn)多數(shù)據(jù)源配置功能

    本文主要講解springboot?+mybatisplus?+?druid?實現(xiàn)多數(shù)據(jù)源配置功能以及一些必要的準(zhǔn)備及代碼說明,具有一定的參考價值,感興趣的小伙伴可以借鑒一下
    2023-06-06
  • JAVA像SQL一樣對List對象集合進(jìn)行排序

    JAVA像SQL一樣對List對象集合進(jìn)行排序

    這篇文章主要介紹了JAVA像SQL一樣對List對象集合進(jìn)行排序的實現(xiàn)方法,文中講解非常細(xì)致,代碼幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下
    2020-07-07
  • java.io.EOFException: Unexpected end of ZLIB input stream異常解決

    java.io.EOFException: Unexpected end of 

    本文主要介紹了java.io.EOFException: Unexpected end of ZLIB input stream異常解決,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-05-05
  • JavaSwing BorderLayout 邊界布局的實現(xiàn)代碼

    JavaSwing BorderLayout 邊界布局的實現(xiàn)代碼

    這篇文章主要介紹了JavaSwing BorderLayout 邊界布局的實現(xiàn)代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-12-12
  • 基于JavaMail的Java實現(xiàn)簡單郵件發(fā)送功能

    基于JavaMail的Java實現(xiàn)簡單郵件發(fā)送功能

    這篇文章主要為大家詳細(xì)介紹了基于JavaMail的Java實現(xiàn)簡單郵件發(fā)送功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-09-09
  • Dubbo3和Spring?Boot整合過程源碼解析

    Dubbo3和Spring?Boot整合過程源碼解析

    Dubbo首先是提供了一個單獨的模塊來和Spring Boot做整合,利用 Spring Boot自動裝配的功能,配置了一堆自動裝配的組件,本文介紹Dubbo3和Spring?Boot整合過程,需要的朋友一起看看吧
    2023-08-08
  • 20秒教你學(xué)會java?List函數(shù)排序操作示例

    20秒教你學(xué)會java?List函數(shù)排序操作示例

    這篇文章主要為大家介紹了20秒教你學(xué)會List函數(shù)排序操作示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-09-09
  • SpringCloud2020版本配置與環(huán)境搭建教程詳解

    SpringCloud2020版本配置與環(huán)境搭建教程詳解

    這篇文章主要介紹了SpringCloud2020版本配置與環(huán)境搭建教程詳解,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-12-12

最新評論