统一结果封装返回结果
**
* 返回信息
* @param <T>
*/
public class R<T> implements Serializable {
/**
* 状态码
*/
private int code;
/**
* 是否成功
*/
private boolean success;
/**
* 返回消息
*/
private String msg;
/**
* 承载数据
*/
private T data;
public R() { }
private R(IResultCode resultCode){
this(resultCode, (T) null,resultCode.getMessage());
}
private R(IResultCode resultCode, T data) {
this(resultCode, data, resultCode.getMessage());
}
private R(IResultCode resultCode, T data, String msg) {
this(resultCode.getCode(), data, msg);
}
private R(int code,T data,String msg){
this.code = code;
this.data = data;
this.msg = msg;
this.success = ResultCode.SUCCESS.code == code;
}
public static <T> R<T> data(T data) {
return data(data, "操作成功");
}
public static <T> R<T> data(T data, String msg) {
return data(200, data, msg);
}
public static <T> R<T> data(int code, T data, String msg) {
return new R(code, data, data == null ? "暂无承载数据" : msg);
}
public static <T> R<T> success(String msg) {
return new R(ResultCode.SUCCESS, msg);
}
public static <T> R<T> success(IResultCode resultCode) {
return new R(resultCode);
}
public static <T> R<T> success(IResultCode resultCode, String msg) {
return new R(resultCode, msg);
}
public static <T> R<T> fail(String msg) {
return new R(ResultCode.FAILURE, msg);
}
public static <T> R<T> fail(int code, String msg) {
return new R(code, (Object)null, msg);
}
public static <T> R<T> fail(IResultCode resultCode) {
return new R(resultCode);
}
public static <T> R<T> fail(IResultCode resultCode, String msg) {
return new R(resultCode, msg);
}
public static <T> R<T> status(boolean flag) {
return flag ? success("操作成功") : fail("操作失败");
}
public int getCode() { return code; }
public void setCode(int code) { this.code = code; }
public boolean isSuccess() { return success; }
public void setSuccess(boolean success) { this.success = success; }
public String getMsg() { return msg; }
public void setMsg(String msg) { this.msg = msg; }
public T getData() { return data; }
public void setData(T data) { this.data = data; }
}
返回结果枚举
@Getter
@AllArgsConstructor
public enum ResultCode implements IResultCode {
/**
* 操作成功
*/
SUCCESS(200,"操作成功"),
/**
* 业务异常
*/
FAILURE(400, "业务异常"),
/**
* 用户名或密码错误
*/
ACCOUNT_OR_PASSWORD_INCORRECT(401, "用户名或密码错误"),
/**
* 用户未登录
*/
NOT_LOGIN(401,"用户未登录或登录状态失效,请重新登录"),
/**
* 请求未授权
*/
UN_AUTHORIZED(403, "请求未授权");
/**
* 状态码
*/
final int code;
/**
* 返回消息
*/
final String message;
}
返回枚举接口
public interface IResultCode extends Serializable {
/**
* 消息
*/
String getMessage();
/**
* 状态码
*/
int getCode();
}
标签:返回,code,封装,data,msg,return,resultCode,RESTFUL,public
From: https://www.cnblogs.com/ldy731729142/p/16794179.html