项目中分页使用的是PageHelper分页插件,先看一下配置
pom.xml文件
<!-- pagehelper 分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
</dependency>
yml文件中
# PageHelper分页插件
pagehelper:
helperDialect: mysql
supportMethodsArguments: true
params: count=countSql
业务需求:表格打开,默认按照create_time进行降序排列,然后也可以根据表格的任意一列,进行动态排序,代码如下:
@PostMapping("/list")
@ResponseBody
public TableDataInfo list(AreaInfo areaInfo)
{
if (areaInfo.getParams().get("orderByColumn") == null){
ServletUtils.getRequest().setAttribute("orderByColumn","create_time");
}
if (areaInfo.getParams().get("isAsc") == null){
ServletUtils.getRequest().setAttribute("isAsc","desc");
}
startPage();
List<AreaInfo> list = areaInfoService.selectAreaInfoList(areaInfo);
return getDataTable(list);
}
startPage()方法
/**
* 设置请求分页数据
*/
protected void startPage()
{
PageDomain pageDomain = TableSupport.buildPageRequest();
Integer pageNum = pageDomain.getPageNum();
Integer pageSize = pageDomain.getPageSize();
if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
{
String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
PageHelper.startPage(pageNum, pageSize, orderBy);
}
}
TableSupport.buildPageRequest()方法实现
public class TableSupport
{
/**
* 封装分页对象
*/
public static PageDomain getPageDomain()
{
PageDomain pageDomain = new PageDomain();
pageDomain.setPageNum(ServletUtils.getParameterToInt(Constants.PAGE_NUM));
pageDomain.setPageSize(ServletUtils.getParameterToInt(Constants.PAGE_SIZE));
pageDomain.setOrderByColumn(ServletUtils.getParameter(Constants.ORDER_BY_COLUMN));
pageDomain.setIsAsc(ServletUtils.getParameter(Constants.IS_ASC));
return pageDomain;
}
public static PageDomain buildPageRequest()
{
return getPageDomain();
}
}
Constants枚举类部分代码
public class Constants
{
/**
* 当前记录起始索引
*/
public static final String PAGE_NUM = "pageNum";
/**
* 每页显示记录数
*/
public static final String PAGE_SIZE = "pageSize";
/**
* 排序列
*/
public static final String ORDER_BY_COLUMN = "orderByColumn";
/**
* 排序的方向 "desc" 或者 "asc".
*/
public static final String IS_ASC = "isAsc";
}
SqlUtil工具类
public class SqlUtil
{
/**
* 仅支持字母、数字、下划线、空格、逗号(支持多个字段排序)
*/
public static String SQL_PATTERN = "[a-zA-Z0-9_\\ \\,]+";
/**
* 检查字符,防止注入绕过
*/
public static String escapeOrderBySql(String value)
{
if (StringUtils.isNotEmpty(value) && !isValidOrderBySql(value))
{
return StringUtils.EMPTY;
}
return value;
}
/**
* 验证 order by 语法是否符合规范
*/
public static boolean isValidOrderBySql(String value)
{
return value.matches(SQL_PATTERN);
}
}