前后端分离:高复用服务响应对象的设计与使用

高复用服务响应对象的设计与使用

一.什么是高复用服务响应对象?它有什么作用?

  1.这次项目中,为了实现前后端分离,设计了一个所有接口都使用,封装后台业务数据放回json数据给前端的对象,用于实现前后端的分离,开发效率有了明显的提高。 

二.怎么使用?

  1.首先,要明确,这个对象要实现序列化接口。它主要封装了三个属性,泛型的返回数据,字符串类型的提示信息以及整型的状态码,以及四个私有的构造函数,需要注意的是,当T 的类型也就是数据类型是String类型时,好像会和下面的String msg重合,到底会调用哪一个呢?答案是,当T为String时,的确会调用第二个,这样会产生一个问题,就是当返回的数据就是String,如果这样就会用到msg的那个构造函数,传到信息那边去了。解决方法在后面,所以具体如下://保证在序列化json时,如果为空的值,key也会消失,比如只要返回状态码时,msg和data就会忽略不返回

//保证在序列化json时,如果为空的值,key也会消失
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
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,String msg){
        this.status = status;
        this.msg = msg;
    }
    private ServerResponse(int status,String msg,T data){
        this.status = status;
        this.msg = msg;
        this.data = data;
    }
    private ServerResponse(int status,T data){
        this.data = data;}

 

2.成员变量的get方法,以及一个判断状态码或者说判断响应是否成功的方法,具体如下:

@JsonIgnore//在序列化时忽略
    public boolean isSuccess(){
        return this.status==ResponseCode.SUCCESS.getCode();
    }
    public int getStatus(){
        return status;
    }
    public String getMsg(){
        return msg;
    }
    public T getData(){
        return data;
    }

3.提供对外访问的七个构造方法,成功的有四个,失败的三个,具体如下:

public static  <T> ServerResponse<T> creatBySuccess(){
        return new ServerResponse<T>(ResponseCode.SUCCESS.getCode());
    }
    public static  <T> ServerResponse<T> creatBySuccessMessage(String msg){
        return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(),msg);
    }
    public static  <T> ServerResponse<T> creatBySuccess(T data){
        return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(),data);
    }
  //这个方法就解决了msg和String类型的数据冲突的问题
public static <T> ServerResponse<T> creatBySuccess(String msg,T data){ return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(),msg,data); } public static <T> ServerResponse<T> creatByError(){ return new ServerResponse<T>(ResponseCode.ERROR.getCode(),ResponseCode.ERROR.getDesc()); } public static <T> ServerResponse<T> creatByErrorMessage(String errorMessage){ return new ServerResponse<T>(ResponseCode.ERROR.getCode(),errorMessage); } public static <T> ServerResponse<T> creatByErrorCodeMessage(int errorCode,String errorMessage){ return new ServerResponse<T>(errorCode,errorMessage); }

三.总结

  这次的高复用服务响应对象的设计与使用涉及到泛型类,后端的数据的处理模式,枚举类的使用,以及前后端数据交互等知识,在后期使用Restlet Clint进行接口功能测试时更加直观地看到了这个对象的作用。

猜你喜欢

转载自www.cnblogs.com/JimmyFanHome/p/9904557.html