Java接口统一返回数据结构封装

1、状态枚举

package com.ntan520.core.result;

/**
 * @author Nick Tan
 */public enum ResultEnum {

    /**
     * 200: 成功
     */    SUCCESS(200, "成功"),
    /**
     * 404: 不存在
     */    NOT_FOUND(404, "资源不存在"),
    /**
     * 403: 无权限
     */    FORBIDDEN(403, "没有权限访问"),
    /**
     * 400: 参数错误
     */    INVALID_REQUEST(400, "Invalid Request"),
    /**
     * 405: 请求方式不支持
     */    METHOD_NOT_ALLOWED(405, "Method Not Allowed"),
    /**
     * 406
     */    NOT_ACCEPTABLE(406, "Not Acceptable"),
    /**
     * 500
     */    INTERNAL_SERVER_ERROR(500, "Internal Server Error"),
    /**
     * 999: 未知异常
     */    UNKNOW_ERROR(999, "未知错误");

    private int code;

    private String message;

    private ResultEnum(int code, String message) {
        this.code = code;
        this.message = message;
    }

    public int getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }
}

2、数据接口定义

package com.ntan520.core.result;

/**
 * @author Nick Tan
 */public interface Response {

}

3、返回数据结构

package com.ntan520.core.result;

/**
 * @author Nick Tan
 */public class Result {

    private int status = ResultEnum.SUCCESS.getCode();

    private String message = ResultEnum.SUCCESS.getMessage();

    private Response data;

    public static Result instance(int code, String message, Response data) {
        return new Result(code, message, data);
    }

    public static Result instance(Response data) {
        return new Result(data);
    }

    public static Result instance() {
        return new Result();
    }

    public Result() {
    }

    public Result(int status, String message, Response data) {
        this.status = status;
        this.message = message;
        this.data = data;
    }

    public Result(Response data) {
        this.data = data;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public Response getData() {
        return data;
    }

    public void setData(Response data) {
        this.data = data;
    }
}

1人评论了“Java接口统一返回数据结构封装”

  1. Pingback: SpringBoot接口参数加密解密 – 梓潼

发表评论