You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
j2ee1/src/main/java/com/utils/Query.java

112 lines
3.1 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package com.utils;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import com.baomidou.mybatisplus.plugins.Page;
/**
* 查询参数类,用于封装分页和排序信息
*/
public class Query<T> extends LinkedHashMap<String, Object> {
private static final long serialVersionUID = 1L;
// mybatis-plus分页参数
private Page<T> page;
// 当前页码
private int currPage = 1;
// 每页条数
private int limit = 10;
/**
* 构造函数使用JQPageInfo对象初始化查询参数
* @param pageInfo 包含分页和排序信息的JQPageInfo对象
*/
public Query(JQPageInfo pageInfo) {
// 设置分页参数
if (pageInfo.getPage() != null) {
currPage = pageInfo.getPage();
}
if (pageInfo.getLimit() != null) {
limit = pageInfo.getLimit();
}
// 防止SQL注入因为sidx、order是通过拼接SQL实现排序的会有SQL注入风险
String sidx = SQLFilter.sqlInject(pageInfo.getSidx());
String order = SQLFilter.sqlInject(pageInfo.getOrder());
// mybatis-plus分页
this.page = new Page<>(currPage, limit);
// 设置排序字段和顺序
if (StringUtils.isNotBlank(sidx) && StringUtils.isNotBlank(order)) {
this.page.setOrderByField(sidx);
this.page.setAsc("ASC".equalsIgnoreCase(order));
}
}
/**
* 构造函数使用Map对象初始化查询参数
* @param params 包含分页和排序信息的Map对象
*/
public Query(Map<String, Object> params) {
this.putAll(params);
// 设置分页参数
if (params.get("page") != null) {
currPage = Integer.parseInt((String) params.get("page"));
}
if (params.get("limit") != null) {
limit = Integer.parseInt((String) params.get("limit"));
}
// 计算偏移量并放入Map中
this.put("offset", (currPage - 1) * limit);
this.put("page", currPage);
this.put("limit", limit);
// 防止SQL注入因为sidx、order是通过拼接SQL实现排序的会有SQL注入风险
String sidx = SQLFilter.sqlInject((String) params.get("sidx"));
String order = SQLFilter.sqlInject((String) params.get("order"));
this.put("sidx", sidx);
this.put("order", order);
// mybatis-plus分页
this.page = new Page<>(currPage, limit);
// 设置排序字段和顺序
if (StringUtils.isNotBlank(sidx) && StringUtils.isNotBlank(order)) {
this.page.setOrderByField(sidx);
this.page.setAsc("ASC".equalsIgnoreCase(order));
}
}
/**
* 获取mybatis-plus分页对象
* @return mybatis-plus分页对象
*/
public Page<T> getPage() {
return page;
}
/**
* 获取当前页码
* @return 当前页码
*/
public int getCurrPage() {
return currPage;
}
/**
* 获取每页条数
* @return 每页条数
*/
public int getLimit() {
return limit;
}
}