Loading

Java封装接口统一返回数据模板

这里我使用Hutool中的HttpStatus作为响应状态码的常量类,可以根据项目情况自行替换

/**
 * 返回结果响应类
 *
 * @author 张涵哲
 * @since 2024-09-02 17:19:04
 */
@Getter
public class Result<T> {

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

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

    public static class Ok<T> extends Result<T>{
        private static final String MESSAGE = "ok";
        public Ok() {
            super(HttpStatus.HTTP_OK, MESSAGE, null);
        }
        public Ok(String msg) {
            super(HttpStatus.HTTP_OK, msg, null);
        }
        public Ok(T data) {
            super(HttpStatus.HTTP_OK, MESSAGE, data);
        }
    }

    public static class Fail<T> extends Result<T>{
        private static final String MESSAGE = "fail";
        public Fail() {
            super(HttpStatus.HTTP_OK, MESSAGE, null);
        }
        public Fail(String msg) {
            super(HttpStatus.HTTP_OK, msg, null);
        }
        public Fail(T data) {
            super(HttpStatus.HTTP_OK, MESSAGE, data);
        }
    }

}
posted @ 2021-01-17 14:48  Java小学生丶  阅读(672)  评论(0编辑  收藏  举报