前后端分离-统一返回给前端的json数据格式(RestApi)

package com.zhoujianpeng.project.response;

public class RestResponse {

    private int code;
    private String msg;
    private T data;


    /**
     * 分别提供返回成功和失败的不同的方法
     * 也就是说返回的数据形式是RestResponse所包含的
     * d第一个T :泛型方法的标示,没有实际的意义
     * 第二个返回的数据类型的一种规范
     *这也就是所谓的工厂模式的应用,
     */

    public static  RestResponse success() {
        return new RestResponse<>();
    }

    public static  RestResponse success(T data) {
        RestResponse restResponse = new RestResponse();
        restResponse.setData(data);
        return restResponse;
    }

    public static  RestResponse error(RestCode restCode) {
        RestResponse restResponse = new RestResponse<>(restCode.code, restCode.msg);
        return restResponse;
    }

    public RestResponse() {
        //默认会调用有参的构造函数,默认是成功的
        this(RestCode.OK.code, RestCode.OK.msg);
    }

    public RestResponse(int code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public RestResponse(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }


    public RestResponse(T data) {
        this.data = data;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}
package com.zhoujianpeng.project.response;

/**
 * 返回的code以及返回的message
 */
public enum  RestCode {

    OK(0, "OK"),
    UNKNOW_ERROR(1, "服务异常"),
    WRONG_PAGE(10100, "页码不存在"),
    ;

    RestCode(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public int code;
    public String msg;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

}

可以参考一下别人的这个文章https://blog.csdn.net/OrangeChenZ/article/details/86468642

你可能感兴趣的:(前后端分离-统一返回给前端的json数据格式(RestApi))