1、构建目录结构如下:
2、controller
3、新建一个通用的响应类
其属性有status、msg、data(响应时status总是存在,但msg和data不一定)
因为无法确定data具体指什么,所以需要使用<泛型>
泛型需要序列化(但其实用了SpringBoot,不手动添加也是可以的)
@Getter
public class CommonResponse<T> implements Serializable {
private int status;
private String msg;
private T data;
}
以下不能使用lombok来自动生成,因为比较复杂,lombok只试用于简单的POJO类)
public CommonResponse(int status){
this.status = status;
}
public CommonResponse(int status,String msg){
this.status = status;
this.msg = msg;
}
public CommonResponse(int status,String msg,T data){
this.status = status;
this.msg = msg;
this.data = data;
}
public CommonResponse(int status,T data){
this.status = status;
this.data = data;
}
如果数据就是String类型的,即T为String,那么将会调用
public CommonResponse(int status,String msg)
而不会调用
public CommonResponse(int status,T data)
即数据会传输到msg中,而不会传入data中
如何解决呢?
1、把构造方法封装起来(把上面的public都改成private)
2、成功响应
(1)只返回状态码
在代码中,最好不要直接出现常量(不好维护),所以新加一个枚举类
@Getter
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 description;
ResponseCode(int code,String description){
this.code = code;
this.description = description;
}
}
之后就可以把0改成
ResponseCode.SUCCESS.getCode()
(2)返回状态码+数据
(3)返回状态码+信息
msg和data怎么区分开呢?
给方法改个名就好啦!
(4)返回状态码+数据+信息
总代码如下:
public static <T> CommonResponse <T> createForSuccess(){
return new CommonResponse<T>(ResponseCode.SUCCESS.getCode());
}
public static <T> CommonResponse <T> createForSuccess(T data){
return new CommonResponse<T>(ResponseCode.SUCCESS.getCode(),data);
}
public static <T> CommonResponse <T> createForSuccessMessage(String msg){
return new CommonResponse<T>(ResponseCode.SUCCESS.getCode(),msg);
}
public static <T> CommonResponse <T> createForSuccess(String msg,T data){
return new CommonResponse<T>(ResponseCode.SUCCESS.getCode(),msg,data);
}
3、错误响应
错误是必须要给提示信息的
public static <T> CommonResponse <T> createForError(){
return new CommonResponse<T>(ResponseCode.ERROR.getCode(),ResponseCode.ERROR.getDescription());
}
public static <T> CommonResponse <T> createForError(String msg){
return new CommonResponse<T>(ResponseCode.ERROR.getCode(),msg);
}
public static <T> CommonResponse <T> createForError(int code,String msg){
return new CommonResponse<T>(code,msg);
}
4、此外,通用响应里面常常包括判断响应是否成功