1. 优化ResultBean,统一响应结构
public enum BaseEnum {
/**
* 枚举类 不要在代码中出现魔法值
*/
SUCCESS("请求成功!", 200),
FAIL("请求失败!", 400);
private String msg;
private int code;
BaseEnum(String msg, int code) {
this.msg = msg;
this.code = code;
}
public String getMsg() {
return msg;
}
public int getCode() {
return code;
}
}
@Data
public class ResultBean<T> implements Serializable {
private int code;
private String msg;
private Boolean resultFlag;
private T data;
public static <T> ResultBean successResult(T value) {
ResultBean resultBean = new ResultBean();
resultBean.setCode(BaseEnum.SUCCESS.getCode());
resultBean.setMsg(BaseEnum.SUCCESS.getMsg());
resultBean.setResultFlag(true);
resultBean.setData(value);
return resultBean;
}
public static ResultBean errorResult() {
ResultBean resultBean = new ResultBean();
resultBean.setCode(BaseEnum.FAIL.getCode());
resultBean.setMsg(BaseEnum.FAIL.getMsg());
resultBean.setResultFlag(false);
return resultBean;
}
public static ResultBean errorJson(String msg) {
ResultBean resultBean = new ResultBean();
resultBean.setCode(BaseEnum.FAIL.getCode());
resultBean.setMsg(msg);
resultBean.setResultFlag(false);
return resultBean;
}
public static ResultBean errorJson(String msg, Integer code) {
ResultBean resultBean = new ResultBean();
resultBean.setCode(code);
resultBean.setMsg(msg);
resultBean.setResultFlag(false);
return resultBean;
}
}
2. 改写controller,响应改成统一的响应bean
@GetMapping("/allUser")
public ResultBean getAllUser() {
List<UserEntity> allUsers = userService.getAllUsers();
return ResultBean.successResult(allUsers);
}
image.png
3. 分页插件
@Configuration
@EnableTransactionManagement
@MapperScan("com.chins.springboot.core.dao")
public class MybatisPlusConfig {
@Bean
PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
@Override
public IPage<UserEntity> getAllUsersPage(BasePage basePage) {
Page<UserEntity> userEntityPage = new Page<>(basePage.getCurrentPage(), basePage.getPageSize());
IPage<UserEntity> userEntityIPage = userMapper.selectPage(userEntityPage, null);
return userEntityIPage;
}
image.png
网友评论