这里先简单定义四个状态:101,102,103,200,如下
@AllArgsConstructor
@NoArgsConstructor
@Getter
public enum ResultCode {FAILURE(100, "请求失败"),TOKEN_EXPIRED(101, "请登录"),NO_PERMISSION(102, "无权限"),SUCCESS(200, "请求成功");private Integer code;private String description;
}
数据结构分为两种,一种带分页,一种不带分页。
/**
*
* @author yangyile
* @since 2023-03-18
*/
@AllArgsConstructor
@NoArgsConstructor
@Getter
public class ResultInfo implements Serializable {private Object data;private Integer code;private String msg;private Integer total;public ResultInfo(Object data, Integer code, String msg) {this.data = data;this.code = code;this.msg = msg;}public static ResultInfo success(Object data) {return new ResultInfo(data, ResultCode.SUCCESS.getCode(), "success");}public static ResultInfo success(Object data, Integer total) {return new ResultInfo(data, ResultCode.SUCCESS.getCode(), "success", total);}public static ResultInfo success(Object data, Integer code, String msg) {return new ResultInfo(data, code, msg);}public static ResultInfo success(Object data, Integer code, String msg, Integer total) {return new ResultInfo(data, code, msg, total);}public static ResultInfo fail(Object data, Integer code, String msg) {return new ResultInfo(data, code, msg);}
}
该注解放在类上。告诉spring容器,该类下所有http请求方法返回的数据都会被包装。
@ControllerAdvice(annotations = {ResponseFormat.class})
public class GlobalResponseInterceptor implements ResponseBodyAdvice
@ControllerAdvice注解是Spring3.2中新增的注解,学名是Controller增强器,作用是给Controller控制器添加统一的操作或处理。
@ControllerAdvice(annotations = {ResponseFormat.class}),改行代码的意思就是以@ResponseFormat注解为切入点,@ResponseFormat注解的类的所有controller方法都要经过处理后返回。
参数说明:
@Api(tags = {"系统用户"})
@RestController
@RequestMapping("/user")
@ResponseFormat
public class UserController {@Autowiredprivate IuserService userService;@ApiOperation(value = "获取用户列表", notes = "获取用户列表,支持分页和根据userName关键字查询")@ApiImplicitParams({@ApiImplicitParam(name = "page", value = "", paramType = "query", dataType = "Integer"),@ApiImplicitParam(name = "limit", value = "", paramType = "query", dataType = "String"),@ApiImplicitParam(name = "userName", value = "用户名", paramType = "query", dataType = "String")})@GetMapping("/getUserList")public List
给UserController类添加注解@ResponseFormat,表示其方法返回数据会被全局处理,然后返回。
{"data": [{"id": 2,"userName": "test","password": "123","isEnable": 1,"nickName": null,"avatar": null,"age": null,"birthday": null,"hobby": null,"updateTime": "2023-03-18T12:27:26.000+0000","createTime": "2023-03-18T12:27:26.000+0000"},{"id": 3,"userName": "test","password": "123","isEnable": 1,"nickName": null,"avatar": null,"age": null,"birthday": null,"hobby": null,"updateTime": "2023-03-18T12:35:26.000+0000","createTime": "2023-03-18T12:35:26.000+0000"}],"code": 200,"msg": "success","total": 2
}