本文主要是介绍SpringBoot 如何增强PageHelper入参的健壮性,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
PageHelper.startPage(int pageNum, int pageSize, boolean count)
参数为外部输入,故存在异常输入场景。比如 pageNum
和 pageSize
输入的值 负数
或者 0
,所以引入PageUtils
来对入参进行判断矫正,从而避免引入异常。
第1步:支持配置的方式来修改默认值
page-helper:default-page-num: 1default-page-size: 10max-page-size: 50count-total-or-not: true
第2步:引入PageUtils
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;import java.util.Objects;@Component
public class PageUtils {private static int defaultPageNumber; // 默认显示第几页private static int defaultPageSize; // 默认每页显示多少条数据private static int maxSizePage; // 每页显示条数上限private static boolean isQueryTotalCount; // 每次查询DB时,是否进行count查询@Value("${page-helper.default-page-num:1}")private int pageNumberFromConfig;@Value("${page-helper.default-page-size:10}")private int pageSizeFromConfig;@Value("${page-helper.max-page-size:15}")private int maxSizePerPageFromConfig;@Value("${page-helper.count-total-or-not:true}")private boolean isQueryTotalFromConfig;@PostConstructprivate void init() {defaultPageNumber = pageNumberFromConfig;defaultPageSize = pageSizeFromConfig;maxSizePage = maxSizePerPageFromConfig;isQueryTotalCount = isQueryTotalFromConfig;}public static int getPageNum(Integer pageNum) {if (Objects.isNull(pageNum) || pageNum <= 0) {return defaultPageNumber;} else {return pageNum;}}public static int getPageSize(Integer pageSize) {if (Objects.isNull(pageSize) || pageSize <= 0) {return defaultPageSize;} else if (pageSize > 100) {return maxSizePage;} else {return pageSize;}}public static boolean isQueryTotalCount() {return isQueryTotalCount;}
}
第3步:使用
public List<Student> listStudents(Integer pageNum, Integer PageSize) {PageHelper.startPage(PageUtils.getPageNum(pageNum), PageUtils.getPageSize(PageSize), PageUtils.isQueryTotalCount());PageHelper.orderBy("age asc");List<Student> students = userMapper.listStudents();PageInfo<Student> studentPageInfo = PageInfo.of(students);return students;
}
参考
@PostConstruct 的执行时机
这篇关于SpringBoot 如何增强PageHelper入参的健壮性的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!