- Result類:用于后臺(tái)返回給前臺(tái)的結(jié)果
public class Result {
// 結(jié)果狀態(tài)碼
private Integer code;
// 結(jié)果消息
private String msg;
// 結(jié)果數(shù)據(jù)
private Object data;
public Result() {
super();
}
public Result(Integer code, String msg, Object data) {
this.code = code;
this.msg = msg;
this.data = data;
}
/**
* 根據(jù)狀態(tài)碼枚舉設(shè)置狀態(tài)碼和狀態(tài)信息的值
* @param code 狀態(tài)碼枚舉
*/
public void setResultCode(ResultCode code) {
this.code = code.getCode();
this.msg = code.getMessage();
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
@Override
public String toString() {
return "Result{" +
"code=" + this.code +
", msg='" + this.msg + '\'' +
", data=" + this.data +
'}';
}
}
- ResultCode類:結(jié)果狀態(tài)枚舉
public enum ResultCode {
SUCCESS(10001, "成功"),
FAILURE(10002, "失敗"),
UNKNOWN_ERROR(10003, "未知錯(cuò)誤"),
SYSTEM_INNER_ERROR(10004, "系統(tǒng)繁忙稽亏,請(qǐng)稍后重試"),
PARAM_VALIDATE_SUCCESS(10005, "參數(shù)校驗(yàn)成功"),
/* 參數(shù)錯(cuò)誤:20001-29999 */
PARAM_IS_INVALID(20001, "參數(shù)無效"),
PARAM_IS_BLANK(20002, "參數(shù)為空"),
PARAM_TYPE_BIND_ERROR(20003, "參數(shù)類型錯(cuò)誤"),
PARAM_NOT_COMPLETE(20004, "參數(shù)缺失");
// 結(jié)果狀態(tài)碼
private Integer code;
// 結(jié)果消息
private String message;
ResultCode(Integer code, String message) {
this.code = code;
this.message = message;
}
public Integer getCode() {
return code;
}
public String getMessage() {
return message;
}
}
- ResultUtil類:返回結(jié)果工具類
public class ResultUtil {
/**
* 成功無返回?cái)?shù)據(jù)
* @return
*/
public static Result success() {
Result result = new Result();
result.setResultCode(ResultCode.SUCCESS);
return result;
}
/**
* 成功帶返回?cái)?shù)據(jù)
* @param data 響應(yīng)數(shù)據(jù)
* @return
*/
public static Result success(Object data) {
Result result = new Result();
result.setResultCode(ResultCode.SUCCESS);
result.setData(data);
return result;
}
/**
* 自定義狀態(tài)碼并帶返回?cái)?shù)據(jù)
* @param code 結(jié)果狀態(tài)碼
* @param data 響應(yīng)數(shù)據(jù)
* @return
*/
public static Result success(ResultCode code, Object data) {
Result result = new Result();
result.setResultCode(code);
result.setData(data);
return result;
}
/**
* 失敗不帶返回?cái)?shù)據(jù)
* @return
*/
public static Result failure() {
Result result = new Result();
result.setResultCode(ResultCode.FAILURE);
return result;
}
/**
* 失敗帶返回?cái)?shù)據(jù)
* @param data 響應(yīng)數(shù)據(jù)
* @return
*/
public static Result failure(Object data) {
Result result = new Result();
result.setResultCode(ResultCode.FAILURE);
result.setData(data);
return result;
}
}