封装返回对象
在实际的开发过程中,必然会和前端打交道,这个时候就需要用到了JSON。所以在这里需要统一封装一个返回对象。
首先一个枚举,把我们的code码放进去,方便调用和以后的维护
这里根据自己实际情况的定义code码。其实本人对枚举也不是很熟悉,因为写PHP没有写过枚举类型。。。以后在深入理解吧
package com.haihao.common;
/**
* Created with IntelliJ IDEA.
*
* @Author: haihao 846548324@qq.com
* @Date: 2021/06/24/10:14
* @Description:
*/
public enum ResponseCode {
SUCCESS(0,"SUCCESS"),
ERROR(-1,"ERROR"),
NULLPOINTER(1001,"NULL");
private final int code;
private final String msg;
ResponseCode(int code,String msg){
this.code = code;
this.msg = msg;
}
public int getCode(){
return code;
}
public String getMsg(){
return msg;
}
}
再来封装一个统一的返回对象
package com.haihao.common;
import java.io.Serializable;
/**
* Created with IntelliJ IDEA.
*
* @Author: haihao 846548324@qq.com
* @Date: 2021/06/24/10:14
* @Description:
*/
public class ResponseJson<T> implements Serializable {
private int status;
private String msg;
private T data;
public ResponseJson(int status){
this.status = status;
}
public ResponseJson(int status,T data){
this.status = status;
this.data = data;
}
private ResponseJson(int status,String msg,T data){
this.status = status;
this.msg = msg;
this.data = data;
}
private ResponseJson(int status,String msg){
this.status = status;
this.msg = msg;
}
public int getStatus(){
return status;
}
public T getData(){
return data;
}
public String getMsg(){
return msg;
}
public static <T> ResponseJson<T> codeSuccess(){
return new ResponseJson<T>(ResponseCode.SUCCESS.getCode());
}
public static <T> ResponseJson<T> codeBySuccessMessage(String msg){
return new ResponseJson<>(ResponseCode.SUCCESS.getCode(),msg);
}
public static <T> ResponseJson<T> codeSuccess(T data){
return new ResponseJson<>(ResponseCode.SUCCESS.getCode(),data);
}
public static <T> ResponseJson<T> codeSuccess(String msg,T data){
return new ResponseJson<T>(ResponseCode.SUCCESS.getCode(),msg,data);
}
public static <T> ResponseJson<T> codeError(){
return new ResponseJson<T>(ResponseCode.ERROR.getCode(),ResponseCode.ERROR.getMsg());
}
public static <T> ResponseJson<T> codeErrorMessage(String errorMessage){
return new ResponseJson<T>(ResponseCode.ERROR.getCode(),errorMessage);
}
public static <T> ResponseJson<T> codeErrorCodeMessage(int errorCode,String errorMessage){
return new ResponseJson<T>(errorCode,errorMessage);
}
public static <T> ResponseJson<T> codeErrorNull(String errorMsg){
return new ResponseJson<T>(ResponseCode.NULLPOINTER.getCode(),errorMsg);
}
public static <T> ResponseJson<T> codeError(String msg,T data){
return new ResponseJson<T>(ResponseCode.ERROR.getCode(),msg,data);
}
}
根据自己项目实际情况来定义需要调用的方法。