SpringBoot 如何增强PageHelper入参的健壮性

PageHelper.startPage(int pageNum, int pageSize, boolean count) 参数为外部输入,故存在异常输入场景。比如 pageNumpageSize 输入的值 负数 或者 0,所以引入PageUtils来对入参进行判断矫正,从而避免引入异常。

第1步:支持配置的方式来修改默认值

yaml 复制代码
page-helper:
  default-page-num: 1
  default-page-size: 10
  max-page-size: 50
  count-total-or-not: true

第2步:引入PageUtils

java 复制代码
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;

    @PostConstruct
    private 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步:使用

java 复制代码
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 的执行时机

相关推荐
无风听海7 小时前
ASP.NET Core .NET 10 错误响应体系全景:从 BadRequest 到编译器基础设施
后端·asp.net·.net
文心快码BaiduComate7 小时前
从个人效能到组织资产:文心快码企业版Agent Hub上线,提升团队AI编程效能
前端·后端·程序员
凯瑟琳.奥古斯特7 小时前
力扣1235:加权区间调度最优解
java·python·算法·leetcode·职场和发展
想不到ID了7 小时前
第八篇: 登录注册功能实现
java·javascript
码语智行7 小时前
shp文件生成
java
plainGeekDev8 小时前
AlertDialog → DialogFragment
android·java·kotlin
雪隐8 小时前
个人电脑玩AI00-前言
人工智能·后端
薛定谔的悦8 小时前
光伏-储能-负荷联合预测:给 EMS 装上“预知能力“
java·数据库·人工智能·python·储能
大菜菜小个子8 小时前
template<typename T>使用
java·开发语言·算法
Refrain_zc8 小时前
Android开发: 拒绝 Activity 重建!onConfigurationChanged 实现平板横竖屏无缝切换
java