封装接口数据返回结果集

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

定义接口状态码枚举类
/**
 * 接口处理状态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);
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值