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

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

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

page-helper:
  default-page-num: 1
  default-page-size: 10
  max-page-size: 50
  count-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;

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

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;
}

SpringBoot 如何增强PageHelper入参的健壮性_第1张图片

参考

@PostConstruct 的执行时机

你可能感兴趣的:(SpringBoot,spring,boot,java,后端)