后端统一接口返回状态【模板】
文章目录
- 后端统一接口返回状态【模板】
- 1 .Result类编写
- 2 .Constants类编写
- 3 .更改Controller层下的类return格式
开发过程中,每个接口的返回格式设计都是一样的,这样可以大大提高开发效率。
项目结构如下图:分别创建Result类和Constants接口
1 .Result类编写
-
未使用Lombok插件的Result类代码
package com.wudreamer.springboot2.config; /*** 接口统一返回包装类*/ public class Result {private String code;private String msg;private Object data;public Result() {// 无参构造函数}public Result(String code, String msg, Object data) {this.code = code;this.msg = msg;this.data = data;}public static Result success() {return new Result(Constants.CODE_200, "", null);}public static Result success(Object data) {return new Result(Constants.CODE_200, "", data);}public static Result error(String code, String msg) {return new Result(code, msg, null);}public static Result error() {return new Result(Constants.CODE_500, "系统错误", null);}public String getCode() {return code;}public void setCode(String code) {this.code = code;}public String getMsg() {return msg;}public void setMsg(String msg) {this.msg = msg;}public Object getData() {return data;}public void setData(Object data) {this.data = data;} }
-
使用Lombok插件后的Result类代码
import com.ppj.constants.Constants; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor;/*** 接口统一返回包装类*/ @Data @NoArgsConstructor @AllArgsConstructor public class Result {private String code;private String msg;private Object data;public static Result success() {return new Result(Constants.CODE_200, "", null);}public static Result success(Object data) {return new Result(Constants.CODE_200, "", data);}public static Result error(String code, String msg) {return new Result(code, msg, null);}public static Result error() {return new Result(Constants.CODE_500, "系统错误", null);}}
2 .Constants类编写
存放状态码
java">package com.wudreamer.springboot2.config;public interface Constants {String CODE_200 = "200"; //成功String CODE_401 = "401"; // 权限不足String CODE_400 = "400"; // 参数错误String CODE_500 = "500"; // 系统错误String CODE_600 = "600"; // 其他业务异常}
3 .更改Controller层下的类return格式
将返回类型更改为Result、修改return 。
// 查询所有用户@GetMappingpublic Result findAll() {return Result.success(userService.findAll());}// 根据id查询单个用户@GetMapping("/{id}")public Result findById(@PathVariable Integer id) {return Result.success(userService.findById(id));}// 新增单个用户@PostMappingpublic Result insert(@RequestBody User user) {userService.insert(user);return Result.success();}// 修改用户@PutMappingpublic Result update(@RequestBody User user) {userService.update(user);return Result.success();}// 删除单个用户@DeleteMapping("/{id}")public Result delete(@PathVariable Integer id) {userService.delete(id);return Result.success();}