如何處理SpringBoot統一回傳格式
背景
相信大部分後端開發人員在日常開發中都需要和前端對接,當然前後端都是你自己一個人搞的話可以想怎麼玩就怎麼玩,但是我們還是要做到一定的規範性。在前後端分離的專案中後端返回的格式一定要友好,並且固定,不能經常變來變去,不然會對前端的開發人員帶來很多的工作量。
SpringBoot Controller 常見的回傳格式
String
@PostMapping("/test") public String test(){ return "Hello World"; }
postman呼叫結果:
自訂物件
正常回傳
@PostMapping("/getUser") public ActionResult getUser(){ User user = new User(); user.setId(UUID.randomUUID().toString()); user.setName("MrDong"); user.setAge(20); return ActionResult.defaultOk(user); }
postman呼叫結果:
錯誤回傳
@PostMapping("/error") public ActionResult error(){ return ActionResult.defaultFail(1000,"服务器异常,请联系管理员"); }
postman呼叫結果:
定義回傳物件
我定義兩個ActionResult這個物件來對回傳值進行封裝,可以根據自己公司實際情況修改:
package com.wxd.entity; import com.wxd.enums.ResultCodeEnum; import lombok.Data; /** * @ClassName ActionResult * @Description 统一返回值封装 * @Author Mr Dong * @Date 2022/7/26 14:51 */ @Data public class ActionResult { private Integer code; private String msg; private Integer count; private Object data; public static ActionResult defaultOk(Integer code, String msg, Integer count, Object data) { return new ActionResult(code, msg, count, data); } public static ActionResult defaultOk(Integer count, Object data) { return new ActionResult(ResultCodeEnum.RC200, count, data); } public static ActionResult defaultOk(Object data) { return new ActionResult(ResultCodeEnum.RC200, null, data); } public static ActionResult defaultOk() { return new ActionResult(ResultCodeEnum.RC200); } public static ActionResult defaultFail() { return new ActionResult(ResultCodeEnum.RC999); } public static ActionResult defaultFail(Integer code, String msg) { return new ActionResult(code, msg); } public static ActionResult defaultFail(ResultCodeEnum resultCodeEnum) { return new ActionResult(resultCodeEnum); } public ActionResult(Integer code, String msg, Integer count, Object data) { this.code = code; this.msg = msg; this.count = count; this.data = data; } public ActionResult(Integer code, String msg) { this.code = code; this.msg = msg; } public ActionResult(ResultCodeEnum resultCodeEnum) { this.code = resultCodeEnum.getCode(); this.msg = resultCodeEnum.getMessage(); } public ActionResult(ResultCodeEnum resultCodeEnum, Integer count, Object data) { this.code = resultCodeEnum.getCode(); this.msg = resultCodeEnum.getMessage(); this.count = count; this.data = data; } }
定義狀態枚舉
package com.wxd.enums; /** * @author wxd * @version V1.0 * @description ResultCodeEnum * @date 2022/8/10 13:35 **/ public enum ResultCodeEnum { /** * 操作成功 */ RC200(200, "操作成功"), /** * 未授权 */ RC401(401, "用户未授权"), /** * 请求被禁止 */ RC403(403, "请求被禁止"), /** * 服务异常 */ RC500(500, "服务器异常,请联系管理员"), /** * 操作失败 */ RC999(999, "操作失败"), RC1001(1001, "用户名密码错误"), RC1002(1002, "未授权的资源"), RC1003(1003, "未授权的资源"), RC1004(1004, "缺少请求参数异常"), RC1005(1005, "缺少请求体参数异常"), RC1006(1006, "参数绑定异常"), RC1007(1007, "方法参数无效异常"); private Integer code; private String message; ResultCodeEnum(Integer code, String message) { this.code = code; this.message = message; } public Integer getCode() { return code; } public String getMessage() { return message; } }
#統一處理返回值及異常
實現原理:需要實現SpringBoot提供的ResponseBodyAdvice這個接口,完成統一傳回值的封裝及異常的處理。實作了這個介面之後,在Controller回傳的時候只需要將物件直接傳回,有些不需要回傳值的可以直接回傳void。
package com.wxd.advice; import com.wxd.entity.ActionResult; import com.wxd.enums.ResultCodeEnum; import lombok.extern.slf4j.Slf4j; import org.springframework.core.MethodParameter; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; import org.springframework.validation.BindException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; /** * @version: V1.0 * @author: wxd * @description: 全局异常处理以及返回值的统一封装 * @Date 2022/7/26 16:24 */ @RestControllerAdvice(value = "com.wxd.controller") @Slf4j public class ResponseAdvice implements ResponseBodyAdvice { @Override public boolean supports(MethodParameter methodParameter, Class aClass) { return true; } /** * 统一包装 * * @param o * @param methodParameter * @param mediaType * @param aClass * @param serverHttpRequest * @param serverHttpResponse * @return */ @Override public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) { /** * String、ActionResult不需要再包一层(不想包一层ActionResult对象的可以在这里把这个对象过滤掉) */ if (o instanceof String || o instanceof ActionResult) { return o; } return ActionResult.defaultOk(o); } /** * 系统内部异常捕获 * * @param e * @return */ @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) @ExceptionHandler(value = Exception.class) public Object exceptionHandler(Exception e) { log.error("系统内部异常,异常信息", e); return ActionResult.defaultFail(ResultCodeEnum.RC500); } /** * 忽略参数异常处理器;触发例子:带有@RequestParam注解的参数未给参数 * * @param e 忽略参数异常 * @return ResponseResult */ @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(MissingServletRequestParameterException.class) public Object parameterMissingExceptionHandler(MissingServletRequestParameterException e) { log.error("缺少Servlet请求参数异常", e); return ActionResult.defaultFail(ResultCodeEnum.RC1004); } /** * 缺少请求体异常处理器;触发例子:不给请求体参数 * * @param e 缺少请求体异常 * @return ResponseResult */ @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(HttpMessageNotReadableException.class) public Object parameterBodyMissingExceptionHandler(HttpMessageNotReadableException e) { log.error("参数请求体异常", e); return ActionResult.defaultFail(ResultCodeEnum.RC1005); } /** * 统一处理请求参数绑定错误(实体对象传参); * * @param e BindException * @return ResponseResult */ @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(BindException.class) public Object validExceptionHandler(BindException e) { log.error("方法参数绑定错误(实体对象传参)", e); return ActionResult.defaultFail(ResultCodeEnum.RC1006); } /** * 统一处理请求参数绑定错误(实体对象请求体传参); * * @param e 参数验证异常 * @return ResponseResult */ @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler({MethodArgumentNotValidException.class}) public Object parameterExceptionHandler(MethodArgumentNotValidException e) { log.error("方法参数无效异常(实体对象请求体传参)", e); return ActionResult.defaultFail(ResultCodeEnum.RC1007); } }
void 無回傳值
有傳回值
以上是如何處理SpringBoot統一回傳格式的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Jasypt介紹Jasypt是一個java庫,它允許開發員以最少的努力為他/她的專案添加基本的加密功能,並且不需要對加密工作原理有深入的了解用於單向和雙向加密的高安全性、基於標準的加密技術。加密密碼,文本,數字,二進位檔案...適合整合到基於Spring的應用程式中,開放API,用於任何JCE提供者...添加如下依賴:com.github.ulisesbocchiojasypt-spring-boot-starter2. 1.1Jasypt好處保護我們的系統安全,即使程式碼洩露,也可以保證資料來源的

一、Redis實現分散式鎖原理為什麼需要分散式鎖在聊分散式鎖之前,有必要先解釋一下,為什麼需要分散式鎖。與分散式鎖相對就的是單機鎖,我們在寫多執行緒程式時,避免同時操作一個共享變數產生資料問題,通常會使用一把鎖來互斥以保證共享變數的正確性,其使用範圍是在同一個進程中。如果換做是多個進程,需要同時操作一個共享資源,如何互斥?現在的業務應用通常是微服務架構,這也意味著一個應用會部署多個進程,多個進程如果需要修改MySQL中的同一行記錄,為了避免操作亂序導致髒數據,此時就需要引入分佈式鎖了。想要實現分

使用場景1、下單成功,30分鐘未支付。支付超時,自動取消訂單2、訂單簽收,簽收後7天未進行評估。訂單超時未評價,系統預設好評3、下單成功,商家5分鐘未接單,訂單取消4、配送超時,推播簡訊提醒…對於延時比較長的場景、即時性不高的場景,我們可以採用任務調度的方式定時輪詢處理。如:xxl-job今天我們採

springboot讀取文件,打成jar包後訪問不到最新開發出現一種情況,springboot打成jar包後讀取不到文件,原因是打包之後,文件的虛擬路徑是無效的,只能通過流去讀取。文件在resources下publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input

在Springboot+Mybatis-plus不使用SQL語句進行多表添加操作我所遇到的問題準備工作在測試環境下模擬思維分解一下:創建出一個帶有參數的BrandDTO對像模擬對後台傳遞參數我所遇到的問題我們都知道,在我們使用Mybatis-plus中進行多表操作是極其困難的,如果你不使用Mybatis-plus-join這一類的工具,你只能去配置對應的Mapper.xml文件,配置又臭又長的ResultMap,然後再寫對應的sql語句,這種方法雖然看上去很麻煩,但具有很高的靈活性,可以讓我們

1.自訂RedisTemplate1.1、RedisAPI預設序列化機制基於API的Redis快取實作是使用RedisTemplate範本進行資料快取操作的,這裡開啟RedisTemplate類,查看該類別的源碼資訊publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations,BeanClassLoaderAware{//聲明了value的各種序列化方式,初始值為空@NullableprivateRedisSe

SpringBoot和SpringMVC都是Java開發中常用的框架,但它們之間有一些明顯的差異。本文將探究這兩個框架的特點和用途,並對它們的差異進行比較。首先,我們來了解一下SpringBoot。 SpringBoot是由Pivotal團隊開發的,它旨在簡化基於Spring框架的應用程式的建立和部署。它提供了一種快速、輕量級的方式來建立獨立的、可執行

在專案中,很多時候需要用到一些配置信息,這些信息在測試環境和生產環境下可能會有不同的配置,後面根據實際業務情況有可能還需要再做修改。我們不能將這些設定在程式碼中寫死,最好是寫到設定檔中,例如可以把這些資訊寫到application.yml檔案中。那麼,怎麼在程式碼裡取得或使用這個位址呢?有2個方法。方法一:我們可以透過@Value註解的${key}即可取得設定檔(application.yml)中和key對應的value值,這個方法適用於微服務比較少的情形方法二:在實際專案中,遇到業務繁瑣,邏
