亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

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

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

一、概念

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

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

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

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

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

2.1 重寫responseAdvice方法

首先,我們需要?jiǎng)?chuàng)建一個(gè)類,實(shí)現(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對(duì)象。

2.2 實(shí)現(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類型的返回值時(shí),會(huì)直接將其寫入響應(yīng)體,而不會(huì)經(jīng)過(guò)HttpMessageConverter,因此我們需要對(duì)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對(duì)象轉(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);
    }
}

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

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

相關(guān)文章

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

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

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

    Java 裝箱與拆箱詳解及實(shí)例代碼

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

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

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

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

    這篇文章主要介紹了JAVA像SQL一樣對(duì)List對(duì)象集合進(jìn)行排序的實(shí)現(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異常解決,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2023-05-05
  • JavaSwing BorderLayout 邊界布局的實(shí)現(xiàn)代碼

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

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

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

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

    Dubbo3和Spring?Boot整合過(guò)程源碼解析

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

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

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

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

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

最新評(píng)論