1.创建返回类
@Getter
@Setter
public class Result<T> {
public Integer code;
public String msg;
public T data;
}
2.创建构造返回类的构造类(注意:我奉行职责单一,两个类也可以合并。看个人)
@Getter
@Setter
public class ResultUtil {
private static <T> Result<T> builder(T data,int code,String msg){
Result<T> result = new Result<>();
result.setData(data);
result.setMsg(msg);
result.setCode(code);
return result;
}
public static <T> Result<T> successData(T data){
return builder(data,HttpState.OK,HttpState.OK_STR);
}
public static Result<Void> successMsg(String msg){
return builder(null,HttpState.OK,msg);
}
public static <T> Result<T> success(T data,String msg){
return builder(data,HttpState.OK,msg);
}
public static Result<Void> success(){
return builder(null,HttpState.OK,HttpState.OK_STR);
}
public static Result<Void> errorMsg(String msg){
return builder(null,HttpState.ERROR,msg);
}
public static Result<Void> error(int code,String msg){
return builder(null,code,msg);
}
public static Result<Void> error(){
return builder(null,HttpState.ERROR, HttpState.ERROR_STR);
}
}
3.使用
/**
* 登录
* @author LXC
* @date 2022/4/27 22:31
*/
@PostMapping(value = "/api/login")
@ApiOperation(value = "登录")
public Result<TokenVo> login(@RequestBody @Validated LoginDto loginDto) {
LoginBo loginBo = BeanUtils.copyProperties(loginDto, LoginBo.class);
TokenVo tokenVo = authService.login(loginBo);
return ResultUtil.success(tokenVo,"登录成功");
}
4.分页统一返回信息类
@Getter
@Setter
public class PageList<T> implements Serializable {
/**
* 总数
* @author LXC
* @date 2022/5/6 9:51
*/
private Long total;
/**
* 总页数
* @author LXC
* @date 2022/5/6 9:51
*/
private Integer totalPage;
/**
* 当前页数
* @author LXC
* @date 2022/5/6 9:52
*/
private Integer nowPage;
/**
* 数据
* @author LXC
* @date 2022/5/6 9:53
*/
private List<T> data;
}
5.分页返回类
@Getter
@Setter
public class PageResult<T> {
private PageList<T> data; // 分页数据
private int code; // 响应码
private String msg; // 响应消息
}
6.分页构造类
public class PageUtils {
public static <T> PageResult<T> getData(List<T> list, Page<?> page){
if(ObjectUtils.isEmpty(list)){
list = new ArrayList<>();
}
int pageNum = 0;
int pages = 0;
long total = 0;
if(!ObjectUtils.isEmpty(page)){
pageNum = page.getPageNum();
pages = page.getPages();
total = page.getTotal();
}
PageResult<T> pageResult = new PageResult<>();
PageList<T> pageList = new PageList<>();
pageList.setData(list);
pageList.setNowPage(pageNum);
pageList.setTotalPage(pages);
pageList.setTotal(total);
pageResult.setData(pageList);
pageResult.setMsg("查询成功");
pageResult.setCode(200);
return pageResult;
}
public static <T> PageResult<T> getData(){
return getData(null,null);
}
}
7.有人使用继承map。有人使用一个类,既是数据返回类也是数据处理类。我个人喜欢分开,代码可读性提高了。
欢迎加入QQ群 619474143,一起学习,一起进步