Custom ResponseResult to encapsulate the controller response information

When developing with a restful api style interface, the specific operation result needs to be encapsulated in the backend. In this process, it is generally customary to write a ResponseCode first, and then write a ResponseResult to make specific success or failure return results Package.

First, define the status information class ResponseCode.
In this class, write some fields agreed upon with the front end, such as code (status code), messge (prompt information), etc.

 	public int id;
    public String msg;

    public ResponseCode(int id, String msg) {
    
    
        this.id = id;
        this.msg = msg;
    }
    /**
     * 系统通用
     * */
    public  static ResponseCode SERVER_SUCCESS = new ResponseCode(500000,"操作成功!");
    public  static ResponseCode SERVER_ERROR = new ResponseCode(500001,"服务器异常");

2. Writing the ResponseResult class.
This class is a specific encapsulation class for the returned data. Here you need to define the information in the ResponseCode and add an uncertain data field, but some people like to re-see a ResultUtil class for different method bodies. , This is good according to this person's habits.

public class ResponseResult<T> {
    
    
    private int code;
    private String msg;
    private T data;
    /**
     * 不同的data数据类型对应不同的ResponseResult的类型
     * */
    
    /**
     *返回 code message data 方法构造器
     * */
    public ResponseResult(ResponseCode rc,T data) {
    
    
        this.data = data;
        this.msg = rc.msg;
        this.code = rc.id;
    }

    /**
     * successful
     * */
    public static <T> ResponseResult<T> success(T data){
    
    
        return new ResponseResult<T>(ResponseCode.SERVER_SUCCESS,data);
    }
    /**
     * error
     * */
    public static  <T> ResponseResult<T> error(T data){
    
    
        return new ResponseResult<T>(ResponseCode.SERVER_ERROR,data);
    }
}

Here we should pay attention to the use of generics in classes and variables. Only two methods are written here, which correspond to the two constructors above. The concrete success/failure/other method constructors can be defined by themselves.

Guess you like

Origin blog.csdn.net/Wangdiankun/article/details/106164877