【写法规范】-- 设计请求返回接口与封装
生活随笔
收集整理的這篇文章主要介紹了
【写法规范】-- 设计请求返回接口与封装
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在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
新人創作打卡挑戰賽發博客就能抽獎!定制產品紅包拿不停!總結
以上是生活随笔為你收集整理的【写法规范】-- 设计请求返回接口与封装的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 阶段1 语言基础+高级_1-3-Java
- 下一篇: jqgrid实现客户端导出Excel、t