在项目开发中,一般返回给前端的都会是一个统一的返回响应对象,因此后端需要封装一个泛型类来作为响应对象,这样做的好处是前后端能统一接口返回,可以做规范的响应处理。
通用返回对象
返回的对象是 状态码
+ 信息
+ 数据
的形式,即接口返回是否成功,数据是什么。
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
|
public class CommonResult<T> { private long code; private String message; private T data;
public CommonResult(long code, String message, T data) { this.code = code; this.message = message; this.data = data; }
public static <T> CommonResult<T> success(T data) { return new CommonResult<T>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(), data); }
public static <T> CommonResult<T> success(T data, String message) { return new CommonResult<T>(ResultCode.SUCCESS.getCode(), message, data); }
public static <T> CommonResult<T> failed(IErrorCode errorCode) { return new CommonResult<T>(errorCode.getCode(), errorCode.getMessage(), null); }
public static <T> CommonResult<T> failed(String message) { return new CommonResult<T>(ResultCode.FAILED.getCode(), message, null); }
public static <T> CommonResult<T> failed() { return failed(ResultCode.FAILED); }
}
|
便捷地插入状态码和信息
定义枚举类 ResultCode 且实现接口 IErrorCode,ResultCode类中可以定义常用的状态码和信息,实现接口的目的是为了提供状态码和信息的setter和getter方法。
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
|
public interface IErrorCode { Long getCode();
String getMessage(); }
public enum ResultCode implements IErrorCode { SUCCESS(200, "操作成功"), FAILED(500, "操作失败");
private long code; private String message;
ResultCode(long code, String message) { this.code = code; this.message = message; }
@Override public Long getCode() { return code; }
@Override public String getMessage() { return message; } }
|
如果有其他类型的返回状态比较常用,也可以添加到代码中。
使用实例
1 2 3 4 5 6
| @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public CommonResult listAll() { List<Employee> employeeList = employeeService.listAll(); return CommonResult.success(employeeList); }
|
该操作返回的对象内容:
- code:200
- message:”操作成功”
- data:List employeeList