在前后端分离开发中,我们前后端交互的内容都是json数据,为了规范我们之间的交互,我们就可以统一结果返回和请求的数据格式。以便我们交流。
统一结果:
@Data
public class RespBean implements Serializable {
@ApiModelProperty(value = "状态码")
private Integer code;
@ApiModelProperty(value = "时间戳")
private Date timestamp;
@ApiModelProperty(value = "提示信息")
private String msg;
@ApiModelProperty(value = "具体数据")
private Map<String,Object> data = new HashMap<String,Object>();
//构造方法私有化
private RespBean(){
}
//成功方法
public static RespBean success() {
RespBean respBean = new RespBean();
respBean.setCode(RespCode.SUCCESS);
respBean.setTimestamp(new Date());
respBean.setMsg("成功了");
return respBean;
}
//失败方法
public static RespBean error() {
RespBean respBean = new RespBean();
respBean.setCode(RespCode.ERROR);
respBean.setTimestamp(new Date());
respBean.setMsg("失败了");
return respBean;
}
在这里采用返回this的形式,可以使得我们继续添加别的属性,在data属性中采用map的数据类型,可以将我们的数据以键值对的形式展示给前端。
//设置提示信息
public RespBean setMsg(String msg) {
this.msg = msg;
return this;
}
//设置状态码
public RespBean setCode(Integer code) {
this.code = code;
return this;
}
//设置时间戳
public RespBean setTimestamp(Date date){
this.timestamp = date;
return this;
}
//设置返回数据
public RespBean setData(String key, Object value) {
this.data.put(key, value);
return this;
}
//设置返回数据
public RespBean setData(Map<String,Object> map) {
this.data = map;
return this;
}
}
样式:
{
"code": 2000,
"timestamp": "2021-10-30 23:36:07",
"msg": "成功了",
"data": {
"navigatePages": 8,
"navigateFirstPage": 1,
"total": 6,
"pages": 1,
"navigatepageNums": [
1
],
"size": 6,
"prePage": 0,
"nextPage": 0,
"pageSize": 6,
"navigateLastPage": 1,
"list": [
{
"report_id": 73,
"report_type": "磁盘IO分布表",
"report_data": "{\"写\": 900, \"读\": 1200, \"型号\": \"MZ-77E500B\", \"磁盘类型\": \"SAS\"}",
"report_time": "2021-10-11 00:00:00",
"create_time": "2021-10-29 14:26:14",
"modify_time": "2021-10-29 14:26:14"
}
],
"pageNum": 1
}
}
统一请求
@Data
@AllArgsConstructor
public class ReqBean implements Serializable {
@ApiModelProperty(value = "时间戳")
private Date timestamp;
@ApiModelProperty(value = "提示信息id")
private String msgid;
@ApiModelProperty(value = "请求来源")
private String source;
@ApiModelProperty(value = "会话")
private String session;
//使用Object类型去接受,可以适配前端所有数据类型,再在service去做具体是数据转换。
@ApiModelProperty(value = "数据项")
private Object data;
public ReqBean() {
}
}
形式:
{
"data": [
{
"report_type": "磁盘IO分布表",
"conditions":{"写":900},
"starttime":"2021-10-10 00:00:00",
"overtime":"2021-10-13 00:00:00",
"pageSize":100,
"pageNum":1
}
],
"msgid": "string",
"session": "string",
"source": "string",
"timestamp": "2021-10-27 12:52:33.797Z"
}