SpringBoot规范统一返回结果集
- 创建响应体
/**
1. @author 苏育科
2. @date 2021-07-28 10:29:10
3. @describe:
*/
@Data
public class ResultData {
@ApiModelProperty("请求响应码")
private int code;
@ApiModelProperty("请求消息体")
private String msg;
@ApiModelProperty("请求响应数据")
private Object data;
public static ResultData success(int code, String msg, Object data) {
return resultData(code, msg, data);
}
public static ResultData fail(int code, String msg) {
return resultData(code, msg, null);
}
public static ResultData fail(int code, Object data, String msg) {
return resultData(code, msg, data);
}
private static ResultData resultData(int code, String msg, Object data) {
ResultData resultData = new ResultData();
resultData.setCode(code);
resultData.setMsg(msg);
resultData.setData(data);
return resultData;
}
}
- 创建枚举类型的响应状态码
/**
1. @author 苏育科
2. @date 2021-07-28 10:33:37
3. @describe:
*/
public enum ResponseCode {
/**
* GET,PUT或DELETE请求成功
*/
SUCCESS(200, "请求成功"),
/**
* 该POST请求是成功的
*/
CREATED(201, "资源创建成功"),
/**
* 缺少API请求的必需属性
*/
BAD_REQUEST(400, "缺少API请求的必需属性"),
/**
* 缺少API用户未经过身份验证
*/
UNAUTHORIZED(401, "用户未经过身份验证"),
/**
* 该请求不被允许
*/
FORBIDDEN(403, "该请求不被允许"),
/**
* 查找不到
*/
NOT_FOUND(404, "查找不到想要的资源"),
/**
* 服务器异常
*/
ERROR(500, "服务器异常");
/**
* 响应状态码
*/
private int val;
/**
* 响应状态信息
*/
private String msg;
ResponseCode(int value, String msg) {
this.val = value;
this.msg = msg;
}
public int val() {
return val;
}
public String msg() {
return msg;
}
}
- 具体应用
@Override
@ApiOperation("查询游戏(分页)")
public ResultData getGamesPage(Integer pageNum, Integer pageSize) {
//1.分页查询数据
PageHelper.startPage(PageUtils.getRightPageNum(pageNum), PageUtils.getRightPageSize(pageSize));
List<GameVo> gameVoList = gameService.getGameVo();
//2.查询数据为空
if (null == gameVoList) {
log.error("[游戏]分页查询游戏为空 pageNum=[{}] pageSize=[{}]", pageNum, pageSize);
return ResultData.fail(ResponseCode.NOT_FOUND.val(), ResponseCode.NOT_FOUND.msg());
}
//3.不为空,封装分页实体类
PageInfo<GameVo> pageInfo = new PageInfo<>(gameVoList);
//4.返回数据
log.info("[游戏]分页查询游戏 pageNum=[{}] pageSize=[{}]", pageNum, pageSize);
return ResultData.success(ResponseCode.SUCCESS.val(), ResponseCode.SUCCESS.msg(), pageInfo);
}
补充一下swagger注释API的三个常用注释说明,上面代码也有用到
@ApiModelProperty: 用在出入参数对象的字段上
@Api: 用于controller类上
@ApiOperation: 用在controller的方法上