工具类之Controller层返回结果封装

一、枚举类ResultCodeEnum

所有返回编码和含义,后续可以自由扩展

/**
 * @program: dc2
 * @description: 返回结果编码与含义
 * @author: Mario
 * @create: 2019-07-22 16:21
 **/
public enum ResultCodeEnum {
    /**
     * 调用成功
     */
    SUCCESS(0, "成功"),

    /**
     * 调用失败
     */
    FAIL(-1, "失败");


    /**
     * 返回编码
     */
    private Integer code;

    /**
     * 编码对应的消息
     */
    private String msg;

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

    /**
     * 获取枚举类型的编码值
     */
    public Integer code() {
        return this.code;
    }

    /**
     * 获取枚举类型的编码含义
     */
    public String msg() {
        return this.msg;
    }

    /**
     * 根据枚举名称--获取枚举编码
     */
    public static Integer getCode(String name) {
        for (ResultCodeEnum resultCode : ResultCodeEnum.values()) {
            if (resultCode.name().equals(name)) {
                return resultCode.code;
            }
        }
        return null;
    }

/*    public static void main(String[] args) {
        System.out.println(ResultCodeEnum.FAIL.code());
        System.out.println(ResultCodeEnum.SUCCESS.msg());
        System.out.println(ResultCodeEnum.getCode("SUCCESS"));
    }*/
}

二、返回结果封装类

/**
 * @program: dc2
 * @description: 返回结果统一封装
 * @author: Mario
 * @create: 2019-07-22 16:21
 **/
@Getter  //这里没有set方法,不让别人通过set给属性赋值
public class ResultUtil implements Serializable {
    private static final long serialVersionUID = 3436477890959388499L;
    
    /**
     * 返回操作码(默认为正常)
     */
    private Integer code = ResultCodeEnum.SUCCESS.code();

    /**
     * 返回数据信息
     */
    private T data;

    /**
     * 返回正确消息信息
     */
    private String msg = "";

    /**
     * 返回错误的消息信息
     */
    private String error = "";

    public static ResultUtil success = new ResultUtil();
    public static ResultUtil fail = new ResultUtil().code(ResultCodeEnum.FAIL.code());

    // 构造方法
    public static ResultUtil build() {
        return new ResultUtil();
    }

    public static  ResultUtil build(T data) {
        return new ResultUtil().data(data);
    }

    // 赋值方法
    public ResultUtil data(T data) {
        this.data = data;
        return this;
    }

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

    public ResultUtil msg(String msg) {
        this.msg = msg;
        return this;
    }

    public ResultUtil error(String error) {
        this.error = error;
        return this;
    }

 /*   public ResultUtil getXxx(){
        Xxx xxx = new Xxx();
        return ResultUtil.build(xxx);
        // return ResultUtil.success.data(xxx).msg("获取成功");
        // return ResultUtil.fail.error("获取失败!");
        // return ResultUtil.fail.code(ResultCodeEnum.FAIL.code()).error("登录过期!");
        // return ResultUtil.fail.code(ResultCodeEnum.FAIL.code()).error(ResultCodeEnum.FAIL.msg());
    }*/
}

 

你可能感兴趣的:(工具类)