1、作为后台的开发人员我们需要根据接口来封装一些后台的一些相应方法,高可用的服务端相应类:
这里我们来总结下:
/** * 服务端的返回响应对象 */ //当程序返回结果失败的时候,此时data是null,这个时候我们不需要返回data的null,利用这个NON_NULL,我们就不返回空的data @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) public class ServerResponse<T> implements Serializable { private int status; private String msg; private T data; private ServerResponse(int status) { this.status = status; } private ServerResponse(int status, T data) { this.status = status; this.data = data; } //这里需要注意的是,如果将private改为public时,是传递给T data呢还是传递给String msg呢,这是需要注意的 private ServerResponse(int status, String msg) { this.status = status; this.msg = msg; } private ServerResponse(int status, String msg, T data) { this.status = status; this.msg = msg; this.data = data; } @JsonIgnore public boolean isSuccess(){ return this.status==ResponseCode.SUCCESS.getCode(); } public int getStatus() { return status; } public String getMsg() { return msg; } public T getData() { return data; } public static <T> ServerResponse<T> createBySuccess(){ return new ServerResponse<T>(ResponseCode.SUCCESS.getCode()); } public static <T> ServerResponse<T> createBySuccessMessage(String msg){ return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(),msg); } public static <T> ServerResponse<T> createBySuccess(T data){ return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(),data); } public static <T> ServerResponse<T> createBySuccess(String msg,T data){ return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(),msg,data); } public static <T> ServerResponse<T> createByError(){ return new ServerResponse<T>(ResponseCode.ERROR.getCode(),ResponseCode.ERROR.getDesc()); } public static <T> ServerResponse<T> createByErrorMessage(String errorMessage){ return new ServerResponse<T>(ResponseCode.ERROR.getCode(),errorMessage); } public static <T> ServerResponse<T> createByErrorCodeMessage(int errorCode,String errorMessage){ return new ServerResponse<T>(errorCode,errorMessage); } }
2、枚举类型的定义:
/** * 定义返回类型的code数据表示 */ public enum ResponseCode { //枚举类:系统为这两个对象默认的加上了public static final SUCCESS(0,"SUCCESS"), ERROR(1,"ERROR"), NEED_LOGIN(10,"NEED_LOGIN"), ILLEGAL_ARGUMENT(2,"ILLEGAL_ARGUMENT"); // 1.枚举类对象的属性不应允许被改动,所以应该使用private final 修饰 private final int code; private final String desc; // 2.枚举类的使用private final 修饰的属性因该在构造器中为其赋值 ResponseCode(int code, String desc) { this.code = code; this.desc = desc; } //供外界调用开放入口 public int getCode() { return code; } public String getDesc() { return desc; } }