SpringBoot《接口返回值統一標準格式》

一、本課程目標:
弄清楚爲什麼要對springboot,所有Controller的response做統一格式封裝?
學會用ResponseBodyAdvice接口 和 @ControllerAdvice註解
二、爲什麼要對response統一格式封裝?
我們先來看下,springboot默認情況下的response是什麼格式的

第一種格式:response爲String
 

@GetMapping(value="/getStr")
public String  getStr(  ){
    return  "test";
}

以上springboot的返回值爲:

test

第二種格式:response爲Objct

@GetMapping(value="/getObject")
public UserVO  getObject(  ){
    UserVO vo=new UserVO();
    vo.setUsername("agan");
    return  vo;
}

以上springboot的返回值爲:

{
  "id": null,
  "username": "agan",
  "password": null,
  "email": null,
  "phone": null,
  "idCard": null,
  "sex": null,
  "deleted": null,
  "updateTime": null,
  "createTime": null
}

第三種格式:response爲void:

@GetMapping(value="/empty")
public void  empty(  ){

}

以上springboot的返回值爲空

第四種格式:response爲異常

@GetMapping(value="/error")
public void  error(  ){
    int i=9/0;
}

以上springboot的返回值爲:

{
  "timestamp": "2019-09-07T10:35:56.658 0000",
  "status": 500,
  "error": "Internal Server Error",
  "message": "/ by zero",
  "path": "/user/error"
} 

以上4種情況,如果你和前端(app、h5)開發人員聯調接口,他們會很懵逼,因爲沒有一個統一response的標準,前端開發人員不知道怎麼處理返回值。故,我們應該統一response的標準格式。

三、定義response的標準格式

一般的response的標準格式包含3部分:1.status狀態值:代表本次請求response的狀態結果。2.response描述:對本次狀態碼的描述。3.data數據:本次返回的數據。

{
   "status":0,
   "message":"成功",
   "data":"test"
}

四、初級程序員對response代碼封裝

對response的統一封裝,是由一定的技術含量的,我們先來看下,初級程序員的封裝,網上很多教程都是這麼寫的。

步驟1:把標準格式轉換爲代碼

{
   "status":0,
   "message":"成功",
   "data":"test"
}

把以上的標準json格式轉換爲ResResult代碼。

package com.techsun.industry.common.base.response;

import com.techsun.industry.common.enums.ResultCode;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@AllArgsConstructor
@NoArgsConstructor
@Data
public class ResResult<T> {  //該類爲api,和web統一的返回格式標準化
    /**
     * 1.status狀態值:代表本次請求response的狀態結果。
     */
    private Integer status;
    /**
     * 2.response描述:對本次狀態碼的描述。
     */
    private String message;
    /**
     * 3.data數據:本次返回的數據。
     */
    private T data;

    /**
     * 成功,創建ResResult:沒data數據
     */
    public static ResResult suc() {
        ResResult result = new ResResult();
        result.setResultCode(ResultCode.SUCCESS);
        return result;
    }

    /**
     * 成功,創建ResResult:有data數據
     */
    public static ResResult suc(Object data) {
        ResResult result = new ResResult();
        result.setResultCode(ResultCode.SUCCESS);
        result.setData(data);
        return result;
    }

    /**
     * 失敗,指定status、desc
     */
    public static ResResult fail(Integer status, String desc) {
        ResResult result = new ResResult();
        result.setStatus(status);
        result.setMessage(desc);
        return result;
    }

    /**
     * 失敗,指定ResultCode枚舉
     */
    public static ResResult fail(ResultCode resultCode) {
        ResResult result = new ResResult();
        result.setResultCode(resultCode);
        return result;
    }

    /**
     * 把ResultCode枚舉轉換爲ResResult
     */
    private void setResultCode(ResultCode code) {
        this.status = code.code();
        this.message = code.message();
    }
}

步驟2:把狀態碼存在枚舉類中


public enum ResultCode {

    /* 成功狀態碼 */
    SUCCESS(200, "成功"),

    /* 系統500錯誤*/
    SYSTEM_ERROR(10000, "系統異常,請稍後重試"),


    /* 參數錯誤:10001-19999 */
    PARAM_IS_INVALID(10001, "參數無效"),


    /* 用戶錯誤:20001-29999*/
    USER_HAS_EXISTED(20001, "用戶已存在"),
    USER_LOGIN_FAIL(20002,"賬號或密碼錯誤"),
    USER_HAS_EXIST(20003,"賬號已存在"),
    USER_NOT_EXIST(20003,"用戶不存在,請重新登錄"),

    /* 認證失敗錯誤:30001-39999*/
    NO_TOKEN(30001,"無token,請重新登錄"),
    TOKEN_OUT_TIME(30002,"token超時,請重新登錄"),
    TOKEN_ILLEGAL(30003,"token 認證失敗"),

    /* 文件失敗錯誤:40001-49999*/
    EXCEL_NO_SHEET(40001,"Excel無Sheet");


    private Integer code;

    private String message;

    ResultCode(Integer code, String message) {
        this.code = code;
        this.message = message;
    }

    public Integer code() {
        return this.code;
    }

    public String message() {
        return this.message;
    }

    public static String getMessage(String name) {
        for (ResultCode item : ResultCode.values()) {
            if (item.name().equals(name)) {
                return item.message;
            }
        }
        return name;
    }

    public static Integer getCode(String name) {
        for (ResultCode item : ResultCode.values()) {
            if (item.name().equals(name)) {
                return item.code;
            }
        }
        return null;
    }

    @Override
    public String toString() {
        return this.name();
    }
}

步驟3:給getResult()方法指定ResResult返回值

@RestController
@RequestMapping("/user")
public class UserController {

    @GetMapping(value="/getResult")
    public ResResult  getResult(  ){
        return ResResult.suc("test");
    }
}

在瀏覽器輸入 http://127.0.0.1:9090/user/getResult 等到以下結果

{
   "status":0,
   "message":"成功",
   "data":"test"
}

看到這裏,應該有很多同學知道這樣封裝代碼有很大的弊端。因爲今後你寫的每個接口,都要手工指定ResResult返回值,如果你在公司推廣你的這種編碼規範,會被人家吐槽和鄙視。

五、高級程序員對response代碼封裝
如果你在公司推廣你的編碼規範,爲了避免被公司其他程序員吐槽和鄙視,我們必須優化代碼。優化的目標:不要每個接口都手工指定ResResult返回值。

步驟1:採用ResponseBodyAdvice技術來實現response的統一格式
springboot提供了ResponseBodyAdvice來幫我們處理ResponseBodyAdvice的作用:攔截Controller方法的返回值,統一處理返回值/響應體,一般用來做response的統一格式、加解密、簽名等等。先看下ResponseBodyAdvice這個接口的源碼。
 

public interface ResponseBodyAdvice<T> {
    /**
    是否支持advice功能
    treu=支持,false=不支持
    **/
    boolean supports(MethodParameter var1, Class<? extends HttpMessageConverter<?>> var2);

    /** 處理response的具體業務方法 */
    @Nullable
    T beforeBodyWrite(@Nullable T var1, MethodParameter var2, MediaType var3, Class<? extends HttpMessageConverter<?>> var4, ServerHttpRequest var5, ServerHttpResponse var6);
}

步驟2:寫一個ResponseBodyAdvice的實現類:


import com.alibaba.fastjson.JSONObject;
import com.techsun.industry.common.base.response.ResResult;
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.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice(basePackages = {"com.*.*.web.controller"}) //controller包路徑
public class ResponseHandler implements ResponseBodyAdvice<Object> {

    /**
     * 是否支持advice功能
     * treu=支持,false=不支持
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    /**
     * 處理response的具體業務方法
     */
    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter,
                                  MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass,
                                  ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (o instanceof String) {
            return  JSONObject.toJSON(JSONObject.toJSONString(ResResult.suc(o)));
        }
        return ResResult.suc(o);
    }

}

使用的是阿里巴巴的fastJson

以上代碼,有2個地方需要重點講解:

第1個地方:@ControllerAdvice 註解:
@ControllerAdvice這是一個非常有用的註解,它的作用是增強Controller的擴展功能類。那@ControllerAdvice對Controller增強了哪些擴展功能呢?主要體現在2方面:

對Controller全局數據統一處理,例如,我們這節課就是對response統一封裝。
對Controller全局異常統一處理,這個後面的課程會詳細講解。
在使用@ControllerAdvice時,還要特別注意,加上basePackages,@ControllerAdvice(basePackages = "com.agan.boot"),因爲如果不加的話,它可是對整個系統的Controller做了擴展功能,它會對某些特殊功能產生衝突,例如 不加的話,在使用swagger時會出現空白頁異常。

第2個地方:beforeBodyWrite方法體的response類型判斷
 

if (o instanceof String) {
            return  JSONObject.toJSON(JSONObject.toJSONString(ResResult.suc(o)));
        }

以上代碼一定要加,因爲Controller的返回值爲String的時候,它是直接返回String,不是json,故我們要手工做下json轉換處理.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章