在項目開發中,通常返回給前端的都會是一個統一的返回響應對象,所以後端須要封裝一個泛型類來做爲響應對象,這樣作的好處是先後端能統一接口返回,能夠作規範的響應處理。前端
ServerResponse類json
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) // 保證序列化json的時候,若是是null的對象,key也會消失 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 ServerResponse(int status, String msg, T data) { this.status = status; this.msg = msg; this.data = data; } private ServerResponse(int status, String msg) { this.status = status; this.msg = msg; }
@JsonIgnore // 使之不在json序列化結果當中 public boolean isSuccess() { return this.status == ResponseCode.SUCCESS.getCode(); } public int getStatus() { return status; } public T getData() { return data; } public String getMsg() { return msg; } 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); } }
ResponseCode枚舉類後端
public enum ResponseCode { SUCCESS(0, "SUCCESS"), ERROR(1, "ERROR"), NEED_LOGIN(10, "NEED_LOGIN"), ILLEGAL_ARGUMENT(2, "ILLEGAL_ARGUMENT"); private final int code; private final String desc; ResponseCode(int code,String desc) { this.code = code; this.desc = desc; } public int getCode() { return code; } public String getDesc() { return desc; } }
沒有什麼說的,直接貼代碼就完事了,實際項目能夠根據實際狀況進行微調。this
"若是隻有這一次,我想我是不會放手的。"spa