Java封装接口统一返回数据模板
这里我使用Hutool中的HttpStatus作为响应状态码的常量类,可以根据项目情况自行替换
方案1 创建返回结果类并利用泛型
/**
* 返回结果响应类
*
* @author 张涵哲
* @since 2024-09-02 17:19:04
*/
@Getter
public class Result<Data> {
private final int code;
private final String msg;
private final Data data;
private static final String OK = "ok";
private static final String FAIL = "fail";
public Result(int code, String msg, Data data) {
this.code = code;
this.msg = msg;
this.data = data;
}
/* ===================== ok ===================== */
public static <T> Result<T> ok() {
return new Result<>(HttpStatus.HTTP_OK, OK, null);
}
public static <T> Result<T> ok(String msg) {
return new Result<>(HttpStatus.HTTP_OK, msg, null);
}
public static <T> Result<T> ok(T data) {
return new Result<>(HttpStatus.HTTP_OK, OK, data);
}
public static <T> Result<T> ok(String msg, T data) {
return new Result<>(HttpStatus.HTTP_OK, msg, data);
}
/* ==================== fail ==================== */
public static <T> Result<T> fail() {
return new Result<>(HttpStatus.HTTP_INTERNAL_ERROR, FAIL, null);
}
public static <T> Result<T> fail(String msg) {
return new Result<>(HttpStatus.HTTP_INTERNAL_ERROR, msg, null);
}
public static <T> Result<T> fail(T data) {
return new Result<>(HttpStatus.HTTP_INTERNAL_ERROR, FAIL, data);
}
public static <T> Result<T> fail(String msg, T data) {
return new Result<>(HttpStatus.HTTP_OK, msg, data);
}
}
方案2 通过Map集合构建返回结果
@Getter
public class Result extends HashMap<String, Object> {
private static final String OK = "ok";
private static final String FAIL = "fail";
private Result() {}
public Result(int code, String msg) {
this.put("code", code);
this.put("msg", msg);
}
/* ===================== ok ===================== */
public static Result ok() {
return new Result(HttpStatus.HTTP_OK, OK);
}
public static Result ok(String msg) {
return new Result(HttpStatus.HTTP_OK, msg);
}
/* ==================== fail ==================== */
public static Result fail() {
return new Result(HttpStatus.HTTP_INTERNAL_ERROR, FAIL);
}
public static Result fail(String msg) {
return new Result(HttpStatus.HTTP_INTERNAL_ERROR, msg);
}
/**
* 向返回结果中追加数据
*
* @author 张涵哲
* @since 2024-11-26 15:54:53
*/
public Result append(String key, Object value) {
this.put(key, value);
return this;
}
/**
* 返回简洁的数据
*
* @author 张涵哲
* @since 2024-11-26 15:55:14
*/
public static Result simple(String key, Object value) {
Result result = new Result();
result.put(key, value);
return result;
}
}
作者多数为原创文章 ( 部分转载已标出 ),目前资历尚浅文章内描述可能有误,对此造成的后果深表歉意,如有错误还望指正

浙公网安备 33010602011771号