该文章仅做记录:
统一定义返回给前端数据格式:
{
"code": 200,
"message": "success",
"data": [
{
"id": 1,
"name": "admin",
"account": "admin",
"roleType": 4
}
]
}
{
"code": 20003,
"message": "验证码已过期",
"data": null
}
定义返回对象,定义返回成功响应,失败响应
成功响应默认给值 code:200,message:success
失败响应返回对应的报错信息。
响应再根据枚举取值
package com.doMyself.exercise.global;
import com.alibaba.fastjson.JSONObject;
import com.doMyself.exercise.exception.BusinessInfo;
import java.io.Serializable;
public class Response<T> implements Serializable {
private Integer code = 200;
private String message = "success";
private T data;
private Response() {
}
private Response success(T data) {
this.data = data;
return this;
}
private Response fail(Integer code, String msg) {
this.code = code;
this.message = msg;
return this;
}
public Response(BusinessInfo businessInfo){
this.code = businessInfo.getCode();
this.message = businessInfo.getMessage();
}
/**
* 成功
* @return
*/
public static Response builderSuccess(){
return builderSuccess(null);
}
/**
* 成功
* @param data
* @return
*/
public static Response builderSuccess(Object data) {
Response response = new Response();
response.setData(data);
return response;
}
/**
* 失败