Restful介面返回統一資料格式
一、定義返回的資料格式:
public class ResponseMessage<T> {
private int code;
private boolean state;
private T data;
private String message;
public ResponseMessage() {
}
public ResponseMessage(boolean state) {
this.state = state;
this.code = getCodeByResult(state);
}
public ResponseMessage(boolean state, String message) {
this.state = state;
this.code = getCodeByResult(state);
this.message = message;
}
public ResponseMessage(int code, boolean state, String message) {
this.code = code;
this.state = state;
this.message = message;
}
public ResponseMessage<T> error(String message) {
return new ResponseMessage<T>(false, message);
}
public ResponseMessage<T> success(String message) {
return new ResponseMessage<T>(true, message);
}
public ResponseMessage<T> success(String message, T data) {
ResponseMessage<T> responseMessage = new ResponseMessage<T>(true, message);
responseMessage.setData(data);
return responseMessage;
}
public ResponseMessage<T> success(T data) {
ResponseMessage<T> responseMessage = new ResponseMessage<T>(true);
responseMessage.setData(data);
return responseMessage;
}
private int getCodeByResult(boolean state) {
return state ? ResultCode.SUCCESS_STATUS.getCode() : ResultCode.NO_DATA_STATUS.getCode();
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public boolean isState() {
return state;
}
public void setState(boolean state) {
this.state = state;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
二、定義狀態碼
public enum ResultCode {
SUCCESS_STATUS(100, "成功!"),
NO_DATA_STATUS(200, "無資料!"),
INTERFACE_BUSINESS_STATUS(300 , "呼叫介面業務錯誤!"),
INTERFACE_ERROR_STATUS(400, "呼叫介面異常!"),
TOKEN_ERROR(500,"token錯誤!"),
TOKEN_OVERDUE(600,"token過期!");
private int code;
private String message;
// 構造方法
private ResultCode(int code, String message) {
this.code = code;
this.message = message;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
/**
* 根據code獲取message
*
* @param code
* @return
*/
public static String getMessage(int code) {
for (ResultCode c : ResultCode.values()) {
if (c.getCode() == code) {
return c.getMessage();
}
}
return null;
}
}