控制层返回统一格式数据

IDE: IDEA
环境: JDK、maven
框架与依赖:springboot、mybatis、Lombok、swagger2

如果有哪个依赖不知道是干嘛的的,建议先自行百度


ResponseCode

enum ResponseCode {
    /*** 通用部分 100 - 599***/
    // 成功请求
    SUCCESS(200, "successful"),
    // 重定向
    REDIRECT(301, "redirect"),
    // 资源未找到
    NOT_FOUND(404, "not found"),
    // 服务器错误
    SERVER_ERROR(500,"server error"),
    /* ... */
    ;

    /**
     * 响应状态码
     */
    private Integer code;
    /**
     * 响应信息
     */
    private String message;

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

    public Integer getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }
}

ResultData

import lombok.Data;

@Data
public class ResultData {

    private Integer code;

    private String msg;

    private Object data;

    private static ResultData resultData(Integer code, String msg, Object data) {
        ResultData resultData = new ResultData();
        resultData.setCode(code);
        resultData.setMsg(msg);
        resultData.setData(data);
        return resultData;
    }

    public static ResultData success(Object data) {
        return resultData(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getMessage(), data);
    }

    public static ResultData success(Object data, String msg) {
        return resultData(ResponseCode.SUCCESS.getCode(), msg, data);
    }

    public static ResultData fail(Integer code, String msg) {
        return resultData(code, msg, null);
    }

    public static ResultData fail(Integer code, String msg, Object data) {
        return resultData(code, msg, data);
    }

}

这里省略其他层,我直接在swagger2上尝试调用,返回数据正常,over~


image.png

你可能感兴趣的:(控制层返回统一格式数据)