前提:SpringBoot整合MyBatis
为了后台返回值统一格式,在util包中创建Result类将返回值封装
public class Result{ private int code; // 状态码 private String msg; // 返回的信息 private T data; // 返回的数据 public static Result success(T data){ return new Result (data); } public static Result success(){ return new Result (); } public static Result error(String msg){ return new Result (msg); } public static Result error(){ return new Result ("error"); } private Result(T data) { this.code = 200; this.msg = "success"; this.data = data; } private Result() { this.code = 200; this.msg = "success"; } private Result(String msg) { this.code = 400; this.msg = msg; } public int getCode() { return code; } public String getMsg() { return msg; } public T getData() { return data; } }
而控制层的getAll方法的返回类型等要改为:
@GetMapping("/getAll")
public Result getAll() {
return Result.success(service.getAll());
}
此时用Postman访问http://localhost:8080/student/getAll得到的结果如下:
当然也可以在封装一个常用异常状态参数的类Error(静态异常可以根据项目自由定义)
public class Error {
private int code; // 状态码
private String msg; // 返回的信息
private Error(int code, String msg) {
this.code = code;
this.msg = msg;
}
// 静态常用异常
public static Error ERROR_1 = new Error(400,"异常类型一");
public static Error ERROR_2 = new Error(500,"异常类型二");
public int getCode() {
return code;
}
public String getMsg() {
return msg;
}
}
然后在Result类中添加如下方法:
public staticResult error(Error error){ return new Result (error); } private Result(Error error) { if (error == null){ return ; } this.code = error.getCode(); this.msg = error.getMsg(); }
使用:
@GetMapping("/getError")
public Result getError() {
return Result.error(ERROR_1);
}
访问http://localhost:8080/student/getError



