SpringBoot統(tǒng)一數(shù)據(jù)返回的幾種方式
在Web應(yīng)用程序開發(fā)中,統(tǒng)一數(shù)據(jù)返回格式對(duì)于前后端分離項(xiàng)目尤為重要。通過統(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": { ... }
}
通過這種方式,前端開發(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)過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);
}
}
在上面的代碼中,我們使用ObjectMapper將ApiResponse對(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);
}
}
通過上述代碼,我們可以實(shí)現(xiàn)Spring Boot項(xiàng)目中統(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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
MyBatis-Plus批量操作SQL日志不打印問題的解決方案
在使用 MyBatis-Plus 的?saveBatch()?和?updateBatchById()?方法進(jìn)行批量數(shù)據(jù)操作時(shí),發(fā)現(xiàn)自定義的 Druid SQL 日志攔截器無法打印這些批量操作的 SQL 語句,導(dǎo)致調(diào)試和問題排查困難,本文給大家該問題的詳細(xì)解決方案,需要的朋友可以參考下2026-03-03
Java線程的創(chuàng)建介紹及實(shí)現(xiàn)方式示例
這篇文章主要為大家介紹了Java線程的創(chuàng)建介紹及實(shí)現(xiàn)方式示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-09-09
SpringMVC請(qǐng)求數(shù)據(jù)詳解講解
Spring MVC 是 Spring 提供的一個(gè)基于 MVC 設(shè)計(jì)模式的輕量級(jí) Web 開發(fā)框架,本質(zhì)上相當(dāng)于 Servlet,Spring MVC 角色劃分清晰,分工明細(xì),本章來講解SpringMVC如何請(qǐng)求數(shù)據(jù)2022-07-07
Java詳細(xì)講解IO流的Writer與Reader操作
Writer與Reader類不能直接調(diào)用,需要使用多帶的方法調(diào)用它們的子類,在他們的前邊加上一個(gè)File即可如(FileWriter或FileReader)的多態(tài)方法進(jìn)行其調(diào)用,并且他們也是抽象類調(diào)用需要連接接口Exception,它們的優(yōu)點(diǎn)在于可以直接寫入或讀出內(nèi)容,不需要使用byte轉(zhuǎn)八進(jìn)制2022-05-05
String與XML互轉(zhuǎn)以及從XML取節(jié)點(diǎn)值并修改的方法
今天小編就為大家分享一篇String與XML互轉(zhuǎn)以及從XML取節(jié)點(diǎn)值并修改的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-07-07

