SpringBoot返回結(jié)果統(tǒng)一處理實(shí)例詳解
一、前言
在Web開發(fā)中,我們常常需要對(duì)API接口的返回結(jié)果進(jìn)行統(tǒng)一的包裝,以方便客戶端對(duì)數(shù)據(jù)和異常情況的統(tǒng)一處理。我們可以自定義返回接口結(jié)果包裝類。
二、創(chuàng)建返回結(jié)果枚舉類
package com.example.hellodemo.enums;
/**
* @author qx
* @date 2023/11/30
* @des 返回結(jié)果枚舉類
*/
public enum ResultTypeEnum {
SUCCESS(0, "成功"), FAILURE(1, "失敗");
private final int code;
private final String msg;
ResultTypeEnum(int code, String msg) {
this.code = code;
this.msg = msg;
}
public int getCode() {
return code;
}
public String getMsg() {
return msg;
}
}三、定義統(tǒng)一返回結(jié)果類
package com.example.hellodemo.bean;
import com.example.hellodemo.enums.ResultTypeEnum;
import java.io.Serializable;
/**
* @author qx
* @date 2023/11/30
* @des 統(tǒng)一返回結(jié)果類
*/
public class ResultResponse<T> implements Serializable {
private int code;
private String msg;
private T data;
public ResultResponse(int code, String msg, T data) {
this.code = code;
this.msg = msg;
this.data = data;
}
public static <T> ResultResponse success() {
return new ResultResponse(ResultTypeEnum.SUCCESS.getCode(), ResultTypeEnum.SUCCESS.getMsg(), null);
}
public static <T> ResultResponse success(T data) {
return new ResultResponse(ResultTypeEnum.SUCCESS.getCode(), ResultTypeEnum.SUCCESS.getMsg(), data);
}
public static <T> ResultResponse success(String msg, T data) {
return new ResultResponse(ResultTypeEnum.SUCCESS.getCode(), msg, data);
}
public static ResultResponse failure() {
return new ResultResponse(ResultTypeEnum.FAILURE.getCode(), ResultTypeEnum.FAILURE.getMsg(), null);
}
public static ResultResponse failure(String msg) {
return new ResultResponse(ResultTypeEnum.FAILURE.getCode(), msg, null);
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}四、創(chuàng)建控制器
package com.example.hellodemo.controller;
import com.example.hellodemo.bean.ResultResponse;
import com.example.hellodemo.bean.one.DbOneEntity;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
/**
* @author qx
* @date 2023/11/30
* @des
*/
@RestController
public class DbController {
@PostMapping("/test")
public ResultResponse<Map<String, Object>> testDemo(@RequestParam String name, @RequestParam Integer id) {
Map<String, Object> hashMap = new HashMap<>();
hashMap.put("name", name);
hashMap.put("id", id);
return ResultResponse.success(hashMap);
}
}測(cè)試:

我們也可以返回自定義的msg。
package com.example.hellodemo.controller;
import com.example.hellodemo.bean.ResultResponse;
import com.example.hellodemo.bean.one.DbOneEntity;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
/**
* @author qx
* @date 2023/11/30
* @des
*/
@RestController
public class DbController {
@PostMapping("/test")
public ResultResponse<Map<String, Object>> testDemo(@RequestParam String name, @RequestParam Integer id) {
Map<String, Object> hashMap = new HashMap<>();
hashMap.put("name", name);
hashMap.put("id", id);
return ResultResponse.success("獲取數(shù)據(jù)成功",hashMap);
}
}測(cè)試:

五、全局異常統(tǒng)一返回類
package com.example.hellodemo.exception;
import com.example.hellodemo.bean.ResultResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* @author qx
* @date 2023/11/30
* @des 全局異常統(tǒng)一返回處理類
*/
@RestControllerAdvice
public class GlobalExceptionHandler {
/**
* 捕獲Exceptino異常類型
*
* @param e
* @return 返回異常統(tǒng)一返回處理結(jié)果
*/
@ExceptionHandler(value = {Exception.class})
public ResultResponse exceptionHandler(Exception e) {
return ResultResponse.failure(e.getMessage());
}
}我們?cè)诳刂破髦凶约簞?chuàng)建一個(gè)異常,然后請(qǐng)求接口,看看返回什么?
package com.example.hellodemo.controller;
import com.example.hellodemo.bean.ResultResponse;
import com.example.hellodemo.bean.one.DbOneEntity;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
/**
* @author qx
* @date 2023/11/30
* @des
*/
@RestController
public class DbController {
@PostMapping("/test")
public ResultResponse<Map<String, Object>> testDemo(@RequestParam String name, @RequestParam Integer id) {
Map<String, Object> hashMap = new HashMap<>();
hashMap.put("name", name);
hashMap.put("id", id);
// 自己寫一個(gè)異常
int i = 1 / 0;
return ResultResponse.success("獲取數(shù)據(jù)成功", hashMap);
}
}測(cè)試:

我們看到msg已經(jīng)返回了異常的相關(guān)信息。
六、Spring切面實(shí)現(xiàn)自動(dòng)返回統(tǒng)一結(jié)果
package com.example.hellodemo.config;
import com.example.hellodemo.bean.ResultResponse;
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.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
/**
* @author qx
* @date 2023/11/30
* @des 全局統(tǒng)一返回結(jié)果
*/
@RestControllerAdvice
public class GlobalResponseAdvice implements ResponseBodyAdvice<Object> {
@Override
public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
return true;
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
// 要排除的api,里面的接口不需要統(tǒng)一包裝
String[] excludePath = {};
for (String path : excludePath) {
if (serverHttpRequest.getURI().getPath().startsWith(path)) {
return body;
}
}
if (body instanceof ResultResponse) {
return body;
}
return ResultResponse.success(body);
}
}我們定義一個(gè)不帶返回格式的控制器。
package com.example.hellodemo.controller;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
/**
* @author qx
* @date 2023/11/30
* @des
*/
@RestController
public class DbController {
@PostMapping("/test")
public Map<String, Object> testDemo(@RequestParam String name, @RequestParam Integer id) {
Map<String, Object> hashMap = new HashMap<>();
hashMap.put("name", name);
hashMap.put("id", id);
return hashMap;
}
}我們進(jìn)行測(cè)試:

我們發(fā)現(xiàn)我們使用切面設(shè)置統(tǒng)一返回結(jié)果的封裝成功了,這樣就統(tǒng)一了返回格式,對(duì)代碼沒有侵入。
我們注意全局異常統(tǒng)一返回和切面使用統(tǒng)一返回結(jié)果都使用了一個(gè)注解@RestControllerAdvice。
以上就是SpringBoot返回結(jié)果統(tǒng)一處理實(shí)例詳解的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot返回結(jié)果統(tǒng)一處理的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- SpringBoot統(tǒng)一數(shù)據(jù)返回格式的實(shí)現(xiàn)示例
- SpringBoot如何統(tǒng)一處理返回結(jié)果和異常情況
- 詳解SpringBoot中的統(tǒng)一結(jié)果返回與統(tǒng)一異常處理
- Springboot設(shè)置統(tǒng)一的返回格式的方法步驟
- 淺析SpringBoot統(tǒng)一返回結(jié)果的實(shí)現(xiàn)
- SpringBoot全局處理統(tǒng)一返回類型方式
- SpringBoot統(tǒng)一返回結(jié)果問題
- 詳解SpringBoot如何統(tǒng)一處理返回的信息
- SpringBoot統(tǒng)一返回格式的方法詳解
- SpringBoot統(tǒng)一數(shù)據(jù)返回的幾種方式
相關(guān)文章
java ThreadPoolExecutor使用方法簡(jiǎn)單介紹
這篇文章主要介紹了java ThreadPoolExecutor使用方法簡(jiǎn)單介紹的相關(guān)資料,需要的朋友可以參考下2017-02-02
Java基于IO流實(shí)現(xiàn)登錄和注冊(cè)功能
這篇文章主要為大家詳細(xì)介紹了Java基于IO流實(shí)現(xiàn)登錄和注冊(cè)功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-04-04
Java interrupt()方法使用注意_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
這篇文章主要介紹了Java interrupt()方法使用注意_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理,需要的朋友可以參考下2017-05-05
Java IO流之原理分類與節(jié)點(diǎn)流文件操作詳解
流(Stream)是指一連串的數(shù)據(jù)(字符或字節(jié)),是以先進(jìn)先出的方式發(fā)送信息的通道,數(shù)據(jù)源發(fā)送的數(shù)據(jù)經(jīng)過這個(gè)通道到達(dá)目的地,按流向區(qū)分為輸入流和輸出流2021-10-10

