通用响应的设计

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、此外,通用响应里面常常包括判断响应是否成功

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值