在前后端分离开发中,我们经常需要统一返回结果对象
1、首先创建一个接口(也可以用枚举和普通类调用final静态变量)统一返回状态码
public interface ResultCode {
public static final Integer SUCCESS = 200;
public static final Integer ERROR = 201;
}
2、创建统一返回结果对象(导入lombok依赖)
import java.util.HashMap;
import java.util.Map;
@Data
public class R {
private Boolean success; //是否成功
private Integer code; //状态码
private String message; //返回消息
private Map<String,Object> data = new HashMap<>(); //返回数据
private R(){}
public static R ok(){
R r = new R();
r.setSuccess(true);
r.setCode(ResultCode.SUCCESS);
r.setMessage("成功");
return r;
}
public static R error(){
R r = new R();
r.setSuccess(false);
r.setCode(ResultCode.ERROR);
r.setMessage("失败");
return r;
}
public R success(Boolean bool){
this.setSuccess(bool);
return this;
}
public R code(Integer code){
this.setCode(code);
return this;
}
public R message(String message){
this.setMessage(message);
return this;
}
public R data(String key,Object value){
this.data.put(key, value);
return this;
}
public R data(Map<String,Object> map){
this.setData(map);
return this;
}
3、创建实体类Student
public class Student {
}
4、开始测试,2步骤的铺垫使得4步骤可以使用链式编程
import java.util.HashMap;
import java.util.Map;
public class MyTest {
public static void main(String[] args) {
Student student = new Student();
//成功返回不带数据
System.out.println(R.ok());
//成功返回带数据
System.out.println(R.ok().data("total", 1).data("items", student));
//成功返回带数据
Map<String,Object> map = new HashMap<>();
map.put("total",1);
map.put("items",student);
System.out.println(R.ok().data(map));
//失败返回
System.out.println(R.error());
System.out.println(R.error().message("返回失败"));
}
}
返回结果