后端从数据库返回的第一手数据结果的格式一般为:{}对象,[]数组 两种,不够统一
所以,需要统一后端返回给前端的数据格式,格式如下:
//统一的返回格式
{
"successs": true,
"code": 666, //响应代码
"message": "成功",
"data": { // data 属性本身是一个HashMap<String,Object>
"key1":[],
"key2":{},
"key3":"",
"key4":6
}
}
//举例1: 列表数据 的返回格式
{
"successs": true,
"code": 666,
"message": "成功",
"data": {
"list": [
{
"name":"teacher1"
"age":52
},{teacher2},{...}
]
}
}
//举例2:分页数据
{
"successs": true,
"code": 666,
"message": "成功",
"data": {
"total":100,//总共的记录数
"pages":5, //返回的总共页数
"rows":[ // 当前页的实际的items
{
"name":"teacher1"
"age":52
},{...},{teacher20}
]
}
}
//举例3:后端返回空数据
{
"successs": true,
"code": 222,
"message": "成功",
"data": {}
}
//举例4:后端返回 失败 的响应状态
{
"successs": false,
"code": 444,
"message": "失败",
"data": {}
}
后端统一返回格式的封装步骤
第一,先定义(响应状态status,响应代码code)接口, 步骤:创建接口,在接口中定义静态成员属性
public interface ResultCode {
public static Integer SUCCESS = 666;
public static Integer ERROR = 444;
}
第二,定义(统一的返回格式)对象,步骤:
创建类,implements步骤一的ResultCode接口;
私有构造器,创建静态方法,返回值是 接口中对应的响应状态 的统一返回格式
public class ResponseResultVO implements ResultCode {
private Integer code; //返回状态码
private String message; //返回消息
private Boolean success; //请求是否成功
private HashMap<String, Object> data = new HashMap<>(); //返回数据
//私有构造器
private ResponseResultVO() {
}
// 创建静态方法, 目的是为每一种响应状态码(ResultCode中的属性)创建对应的统一的返回格式的模板,
public static ResponseResultVO ok() {
ResponseResultVO responseResult = new ResponseResultVO();
responseResult.setSuccess(true);
responseResult.setMessage("成功");
responseResult.setCode(SUCCESS);
return responseResult;
}
public static ResponseResultVO error() {
ResponseResultVO responseResult = new ResponseResultVO();
responseResult.setSuccess(false);
responseResult.setMessage("失败");
responseResult.setCode(ERROR);
return responseResult;
}
//返回举例1的格式 使用方法:
//ResponseResultVO.setSuccess(true).setCode(SUCCESS)
//.setData("key1","").setData("key2",object).setData("key3",list);
public ResponseResultVO success(Boolean success) {
this.setSuccess(success);
return this;
}
public ResponseResultVO message(String message) {
this.setMessage(message);
return this;
}
public ResponseResultVO code(Integer code) {
this.setCode(code);
return this;
}
public ResponseResultVO data(String key, Object value) {
this.data.put(key, value);
return this;
}
public ResponseResultVO data(HashMap<String, Object> data) {
this.data = data;
return this;
}
}
相关文章链接: SpringBoot统一返回格式及参数校验 - 穷苦书生 - 博客园 (cnblogs.com)