有些时候 我们需要封装一个 通用返回类 来承载我们返回的数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
| @Data public class R<T> implements Serializable { private static final long serialVersionUID = 1L;
private static final Integer SUCCESS_CODE = 0; private static final String SUCCESS_MSG = "success";
private static final Integer COMMON_ERROR_CODE = -1;
public Integer code;
public Boolean success;
public String msg;
public T data; public R() { this.msg = SUCCESS_MSG; this.code = SUCCESS_CODE; this.success = true; } public R(String message) { this.msg = message; this.code = SUCCESS_CODE; this.success = true; } public R(T data) { this.msg = SUCCESS_MSG; this.code = SUCCESS_CODE; this.data = data; this.success = true; } public R(Integer code, String message, T data) { this.msg = message; this.code = code; this.data = data; this.success = true; } public static <T> R<T> success() { R<T> r = new R<>(); r.setCode(SUCCESS_CODE); r.setMsg(SUCCESS_MSG); r.setSuccess(true); return r; } public static <T> R<T> success(String msg) { R<T> r = new R<>(); r.setCode(SUCCESS_CODE); r.setMsg(msg); r.setSuccess(true); return r; } public static <T> R<T> success(T data) { R<T> r = new R<>(); r.setCode(SUCCESS_CODE); r.setMsg(SUCCESS_MSG); r.setData(data); r.setSuccess(true); return r; } public static <T> R<T> success(String msg, T data) { R<T> r = new R<>(); r.setCode(SUCCESS_CODE); r.setMsg(msg); r.setData(data); r.setSuccess(true); return r; } public static <T> R<T> error(String msg) { return error(COMMON_ERROR_CODE, msg); } public static <T> R<T> error(int code, String msg) { R<T> r = new R<>(); r.setCode(code); r.setMsg(msg); r.setSuccess(code == SUCCESS_CODE); return r; } public static <T> R<T> error(BaseResponseEnum baseResponse) { return error(baseResponse.getCode(), baseResponse.getMsg()); } }
|
这样我们在 controller 层返回数据的时候 就可以这样
1 2 3
| public R<?> controllerMethod(@RequestParam("params") String params) { return R.success(xxxService.serviceMethod(params)); }
|