封装接口数据返回结果集

谁说我不能喝 提交于 2019-12-27 02:21:05

在前后端完全分离的项目当中,为了方便与前端人员的数据交互,定义返回结果集,封装数据、状态码、错误信息。

定义接口状态码枚举类

/**
 * 接口处理状态code和description 枚举
 */
public enum ResponseCode {
    ERROR(500, "ERROR"),//错误,服务器出BUG
    SUCCESS(200, "SUCCESS"),//请求成功
    WARNING(300, "WARNING");//警告 逻辑错误 登录密码错误等等
    public final int code;
    public final String msg;
    
    ResponseCode(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }
}

利用Java的泛型特性,实现对结果集的封装。

/**
 * 接口数据返回定义类
 * 作用:将需要返回给前端的数据进行包装,同时封装status和msg两个字段并JSON序列化
 * T(泛型) 为返回数据的类型
 */
@Data
@JsonSerialize
public class ServerResponse<T> implements Serializable {

    //接口返回状态
    private Integer status;
    //返回提示信息
    private String msg;
    //返回的数据
    private T data;

    /**
     * 根据成功与否及是否需要返回data提供的各种静态构造方法
     */
    public static <T> ServerResponse<T> createBySuccess() {
        return new ServerResponse<T>(ResponseCode.SUCCESS.code, null, ResponseCode.SUCCESS.msg);
    }

    public static <T> ServerResponse<T> createBySuccess(T data) {
        return new ServerResponse<>(ResponseCode.SUCCESS.code, data, ResponseCode.SUCCESS.msg);
    }

    public static <T> ServerResponse<T> createByError() {
        return new ServerResponse<>(ResponseCode.ERROR.code, null, ResponseCode.ERROR.msg);
    }

    public static <T> ServerResponse<T> createByErrorMsg(String msg) {
        return new ServerResponse<>(ResponseCode.SUCCESS.code, null, msg);
    }

    public static <T> ServerResponse<T> createWarningMsg(String msg) {
        return new ServerResponse<>(ResponseCode.WARNING.code, null, msg);
    }

    private ServerResponse(int status, T data, String msg) {
        this.status = status;
        this.msg = msg;
        this.data = data;
    }
}

使用方式

@RestController
public class UserController{
    /**
     * 登录
     * @param user 账号、密码
     */
    @ArgsNotNull({"user.username","user.password"})
    @PostMapping("login.do")
    public ServerResponse login(User user) {
        //TO DO login
        //使用的 public static <T> ServerResponse<T> createBySuccess(T data){}
        return ServerResponse.createBySuccess(user);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!