日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

【写法规范】-- 设计请求返回接口与封装

發布時間:2025/3/15 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【写法规范】-- 设计请求返回接口与封装 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

在web開發時,請求返回一般有兩類。一類是數據(一般為json格式),一類是頁面。

@GetMapping("/hello")public String hello1(){//這里使用的thymeleaf,會去找hello.htmlreturn "hello";}@ResponseBody@GetMapping("/hello")public String hello2(){//直接返回字符串return "hello lhb";}

這顯然不太規范,會給前后端開發人員之間的溝通和協作帶來麻煩。

正確的做法是設計規范的接口并進行封裝。

服務端返回的數據格式(json)

{"code":0"msg" :"data":{},[] }

code:代表錯誤碼。具體的錯誤碼是需要自定義的,例如:0代表成功,777代表服務器異常等。

msg:代表錯誤信息

data:代表成功時的數據,可以是json對象或數組。

{"code":777"msg" :"服務器異常""data":{} }

接下來讓我們來看一個封裝的實例:

Result類:

public class Result<T> {private int code;private String msg;private T data;/*** 請求成功時調用* @param data* @return*/public static <T> Result<T> success(T data){return new Result<T>(data);}public static <T> Result<T> error(CodeMsg cm){return new Result<T>(cm);}/*** 只傳入數據默認成功,所以添加默認的code和msg* @param data*/private Result(T data) {this.code=0;this.msg="success";this.data=data;}private Result(CodeMsg cm) {if(cm==null){return;}this.code=cm.getCode();this.msg=cm.getMsg();}public int getCode() {return code;}public String getMsg() {return msg;}public T getData() {return data;}} CodeMsg類: public class CodeMsg {private int code;private String msg;//通用的錯誤碼public static CodeMsg SUCCESS = new CodeMsg(0, "success");public static CodeMsg SERVER_ERROR = new CodeMsg(777, "服務端異常");public int getCode() {return code;}public String getMsg() {return msg;}private CodeMsg(int code,String msg) {this.code = code;this.msg = msg;}}

為什么要有CodeMsg類?

如果沒有CodeMsg類,當我們請求返回成功時,可以直接將數據傳入。

@ResponseBody@GetMapping("/hello")public Result<String> hello(){return Result.success("hello");}

但是,如果請求失敗,需要傳遞錯誤信息時,我們必須這么做。

@ResponseBody@GetMapping("/helloerror")public Result<String> helloError(){return Result.error(new CodeMsg(777,"服務器異常"));}

這樣不是不可以,只是看起來不太優雅。而且,如果項目非常大,到后期可能連你自己也不知道自己定義了多少錯誤碼,甚至可能重復定義錯誤碼。

如何優化呢?我們只需要在CodeMsg中定義靜態的成員變量,并且給它賦上自定義的錯誤碼和錯誤信息,這樣不僅看上去規范了許多,而且所有的錯誤類型都在一個地方,方便修改和檢查。

優化后:

@ResponseBody@GetMapping("/helloerror")public Result<String> helloError(){return Result.error(CodeMsg.SERVER_ERROR);}

?

轉載于:https://www.cnblogs.com/jsyllhb/p/10548169.html

新人創作打卡挑戰賽發博客就能抽獎!定制產品紅包拿不停!

總結

以上是生活随笔為你收集整理的【写法规范】-- 设计请求返回接口与封装的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。