/**
* @description:封装json对象,所有返回结果都使用它
**/
public class Result<T> { private int code;// 业务自定义状态码 private String msg;// 请求状态描述,调试用 private T data;// 请求数据,对象或数组均可 public Result() {
} /**
* 成功时候的调用
* @param data data
* @param <T> t
* @return Result
*/
public static <T> Result<T> success(T data){
return new Result<T>(data);
} /**
* 失败时候的调用
* @param codeMsg codeMsg
* @param <T> t
* @return Result
*/
public static <T> Result<T> error(CodeMsg codeMsg){
return new Result<T>(codeMsg);
} /**
* 成功的构造函数
* @param data data
*/
public Result(T data){
this.code = 200;//默认200是成功
this.msg = "SUCCESS";
this.data = data;
} public Result(int code, String msg) {
this.code = code;
this.msg = msg;
} /**
* 失败的构造函数
* @param codeMsg codeMsg
*/
private Result(CodeMsg codeMsg) {
if(codeMsg != null) {
this.code = codeMsg.getCode();
this.msg = codeMsg.getMsg();
}
} public int getCode() {
return code;
} public void setCode(int code) {
this.code = code;
} 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;
} @Override
public String toString() {
return "Result{" +
"code=" + code +
", msg='" + msg + '\'' +
", data=" + data +
'}';
}
}
public class CodeMsg { private int code;
private String msg;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
/*服务端异常*/
public static CodeMsg SUCCESS = new CodeMsg(200,"SUCCESS");
public static CodeMsg SERVER_ERROR = new CodeMsg(100,"系统异常:%s");
public static CodeMsg BIND_ERROR = new CodeMsg(101,"(绑定异常)参数校验异常:%s"); /*用占位符 传入一个参数*/
public static CodeMsg SESSION_ERROR = new CodeMsg(102,"没有SESSION!"); /*用占位符 传入一个参数*/
public static CodeMsg REQUEST_ERROR = new CodeMsg(103,"非法请求!"); /*用占位符 传入一个参数*/
public static CodeMsg REQUEST_OVER_LIMIT = new CodeMsg(104,"请求次数过多!"); /*用占位符 传入一个参数*/ private CodeMsg( ) {
}
private CodeMsg( int code,String msg ) {
this.code = code;
this.msg = msg;
}
//不定参的构造函数
public CodeMsg fillArgs(Object... args) {
int code = this.code;
String message = String.format(this.msg, args);
return new CodeMsg(code, message);
}
@Override
public String toString() {
return "CodeMsg [code=" + code + ", msg=" + msg + "]";
}
}