/**
* Copyright © 2012-2014 JeeSite All rights reserved.
*/
package com.nis.domain;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.mapping.ResultMap;
import org.apache.ibatis.mapping.ResultMapping;
import org.apache.ibatis.session.SqlSessionFactory;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.nis.util.Configurations;
import com.nis.util.Constants;
import com.nis.util.CookieUtil;
import com.nis.util.StringUtil;
import com.nis.web.service.SpringContextHolder;
/**
* 分页类
* @author ThinkGem
* @version 2013-7-2
* @param
*/
public class Page {
private int pageNo = 1; // 当前页码
private int pageSize = Integer.valueOf(Configurations.getIntProperty("page.pageSize", 30)); // 页面大小,设置为“-1”表示不进行分页(分页无效)
private long count;// 总记录数,设置为“-1”表示不查询总数
private int first;// 首页索引
private int last;// 尾页索引
private int prev;// 上一页索引
private int next;// 下一页索引
private boolean firstPage;//是否是第一页
private boolean lastPage;//是否是最后一页
private int length = 8;// 显示页面长度
private int slider = 1;// 前后显示页面长度
private List list = new ArrayList();
private String orderBy = ""; // 标准查询有效, 实例: updatedate desc, name asc
private String fields ="";//制定资源的字段
private String where;
private String funcName = "page"; // 设置点击页码调用的js函数名称,默认为page,在一页有多个分页对象时使用。
private String funcParam = ""; // 函数的附加参数,第三个参数值。
private String message = ""; // 设置提示消息,显示在“共n条”之后
public Page() {
this.pageSize = pageSize;
}
/**
* 构造方法
* @param request 传递 repage 参数,来记住页码
* @param response 用于设置 Cookie,记住页码
*/
public Page(HttpServletRequest request, HttpServletResponse response){
//this(request, response,Integer.valueOf(Configurations.getIntProperty("page.pageSize", 30)));
}
/**
* 构造方法
* @param request 传递 repage 参数,来记住页码
* @param response 用于设置 Cookie,记住页码
*
*/
public Page(HttpServletRequest request, HttpServletResponse response,Class clazz){
this(request, response,clazz.getSimpleName(),Integer.valueOf(Configurations.getIntProperty("page.pageSize", 30)));
}
public Page(HttpServletRequest request, HttpServletResponse response,int defaultPageSize){
this(request, response,"",Integer.valueOf(Configurations.getIntProperty("page.pageSize", 30)));
}
public Page(HttpServletRequest request, HttpServletResponse response,String className, int defaultPageSize){
try {
// 设置页码参数(传递repage参数,来记住页码)
String no = request.getParameter("pageNo");
if (StringUtils.isNotBlank(no)) {
if (StringUtils.isNumeric(no)){
CookieUtil.addCookie(response, "pageNo", no);
this.setPageNo(Integer.parseInt(no));
}else if (request.getParameter("repage")!=null){
no = CookieUtil.getValue(request, "pageNo");
if (StringUtils.isNumeric(no)){
this.setPageNo(Integer.parseInt(no));
}
}
}
// 设置页面大小参数(传递repage参数,来记住页码大小)
String size = request.getParameter("pageSize");
if (StringUtils.isNotBlank(size)) {
if (StringUtils.isNumeric(size) || size.equals("-1")){
CookieUtil.addCookie(response, "pageSize", size);
this.setPageSize(Integer.parseInt(size));
} else if (request.getParameter("repage")!=null){
size = CookieUtil.getValue(request, "pageSize");
if (StringUtils.isNumeric(size)){
this.setPageSize(Integer.parseInt(size));
}
}
} else {
this.pageSize = defaultPageSize;
}
//超出每页最大显示条数,取限制的最大条数
if(this.pageSize > Constants.MAX_PAGE_SIZE){
this.pageSize = Constants.MAX_PAGE_SIZE;
}
String fields = request.getParameter("fields");
if (StringUtils.isNotBlank(fields)){
fields=getFiledsSql(className, fields);
this.setFields(fields);
}
// 设置排序参数
String orderBy = request.getParameter("orderBy");
if (StringUtils.isNotBlank(orderBy)){
orderBy=getOrderBySql(className, orderBy);
this.setOrderBy(orderBy);
}
this.count=Integer.valueOf(Configurations.getIntProperty("page.count", -1));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
* @Title: getWhere
* @Description: TODO(抽取where查询条件)
* @param @param request
* @param @return 入参
* @return String 返回类型
* @author (darnell)
* @throws
* @date 2016年8月17日 上午9:28:21
* @version V1.0
*/
private String getWhere(HttpServletRequest request) {
Map requestMap = request.getParameterMap();
StringBuilder whereBuilder = new StringBuilder(512);
for(String paramName : request.getParameterMap().keySet()) {
if (paramName.startsWith("search")) {
whereBuilder.append(paramName.substring("search_".length()))
.append("=").append(requestMap.get(paramName)[0]).append(" and ");
}
}
if (whereBuilder.length() > 0) {
whereBuilder.delete(whereBuilder.lastIndexOf(" and "), whereBuilder.length());
}
return whereBuilder.toString();
}
/**
* 构造方法
* @param pageNo 当前页码
* @param pageSize 分页大小
*/
public Page(int pageNo, int pageSize) {
this(pageNo, pageSize, 0);
}
/**
* 构造方法
* @param pageNo 当前页码
* @param pageSize 分页大小
* @param count 数据条数
*/
public Page(int pageNo, int pageSize, long count) {
this(pageNo, pageSize, count, new ArrayList());
}
/**
* 构造方法
* @param pageNo 当前页码
* @param pageSize 分页大小
* @param count 数据条数
* @param list 本页数据对象列表
*/
public Page(int pageNo, int pageSize, long count, List list) {
this.setCount(count);
this.setPageNo(pageNo);
this.pageSize = pageSize;
this.list = list;
}
/**
* 初始化参数
*/
public void initialize(){
//1
this.first = 1;
this.last = (int)(count / (this.pageSize < 1 ? 20 : this.pageSize) + first - 1);
if (this.count % this.pageSize != 0 || this.last == 0) {
this.last++;
}
if (this.last < this.first) {
this.last = this.first;
}
if (this.pageNo <= 1) {
this.pageNo = this.first;
this.firstPage=true;
}
if (this.pageNo >= this.last) {
this.pageNo = this.last;
this.lastPage=true;
}
if (this.pageNo < this.last - 1) {
this.next = this.pageNo + 1;
} else {
this.next = this.last;
}
if (this.pageNo > 1) {
this.prev = this.pageNo - 1;
} else {
this.prev = this.first;
}
//2
if (this.pageNo < this.first) {// 如果当前页小于首页
this.pageNo = this.first;
}
if (this.pageNo > this.last) {// 如果当前页大于尾页
this.pageNo = this.last;
}
}
/**
* 默认输出当前分页标签
* ${page}
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (pageNo == first) {// 如果是首页
sb.append("« 上一页 \n");
} else {
sb.append("« 上一页 \n");
}
int begin = pageNo - (length / 2);
if (begin < first) {
begin = first;
}
int end = begin + length - 1;
if (end >= last) {
end = last;
begin = end - length + 1;
if (begin < first) {
begin = first;
}
}
if (begin > first) {
int i = 0;
for (i = first; i < first + slider && i < begin; i++) {
sb.append(""
+ (i + 1 - first) + " \n");
}
if (i < begin) {
sb.append("... \n");
}
}
for (int i = begin; i <= end; i++) {
if (i == pageNo) {
sb.append("" + (i + 1 - first)
+ " \n");
} else {
sb.append(""
+ (i + 1 - first) + " \n");
}
}
if (last - end > slider) {
sb.append("... \n");
end = last - slider;
}
for (int i = end + 1; i <= last; i++) {
sb.append(""
+ (i + 1 - first) + " \n");
}
if (pageNo == last) {
sb.append("下一页 » \n");
} else {
sb.append(""
+ "下一页 » \n");
}
sb.append("当前 ");
sb.append(" / ");
sb.append(" 条,");
sb.append("共 " + count + " 条"+(message!=null?message:"")+" \n");
sb.insert(0,"\n");
sb.append("
");
// sb.insert(0,"\n").append("
\n");
return sb.toString();
}
/**
* 获取分页HTML代码
* @return
*/
@JsonIgnore
public String getHtml(){
return toString();
}
// public static void main(String[] args) {
// Page p = new Page(3, 3);
// System.out.println(p);
// System.out.println("首页:"+p.getFirst());
// System.out.println("尾页:"+p.getLast());
// System.out.println("上页:"+p.getPrev());
// System.out.println("下页:"+p.getNext());
// }
/**
* 获取设置总数
* @return
*/
public long getCount() {
return count;
}
/**
* 设置数据总数
* @param count
*/
public void setCount(long count) {
this.count = count;
if (pageSize >= count){
pageNo = 1;
}
}
/**
* 获取当前页码
* @return
*/
public int getPageNo() {
return pageNo;
}
/**
* 设置当前页码
* @param pageNo
*/
public void setPageNo(int pageNo) {
this.pageNo = pageNo;
}
/**
* 获取页面大小
* @return
*/
public int getPageSize() {
return pageSize;
}
/**
* 设置页面大小(最大500)
* @param pageSize
*/
public void setPageSize(int pageSize) {
if (pageSize == -1 || pageSize > 0 ) {
this.pageSize = pageSize;
} else {
this.pageSize = Integer.valueOf(Configurations.getIntProperty("page.pageSize", 30));
}
}
/**
* 首页索引
* @return
*/
@JsonIgnore
public int getFirst() {
return first;
}
/**
* 尾页索引
* @return
*/
public int getLast() {
return last;
}
/**
* 获取页面总数
* @return getLast();
*/
@JsonIgnore
public int getTotalPage() {
return getLast();
}
/**
* 是否为第一页
* @return
*/
@JsonIgnore
public boolean isFirstPage() {
return firstPage;
}
/**
* 是否为最后一页
* @return
*/
@JsonIgnore
public boolean isLastPage() {
return lastPage;
}
/**
* @return where
*/
@JsonIgnore
public String getWhere() {
return where;
}
/**
* @param where 要设置的 where
*/
public void setWhere(String where) {
this.where = where;
}
/**
* 上一页索引值
* @return
*/
@JsonIgnore
public int getPrev() {
if (isFirstPage()) {
return pageNo;
} else {
return pageNo - 1;
}
}
/**
* 下一页索引值
* @return
*/
@JsonIgnore
public int getNext() {
if (isLastPage()) {
return pageNo;
} else {
return pageNo + 1;
}
}
/**
* 获取本页数据对象列表
* @return List
*/
public List getList() {
return list;
}
/**
* 设置本页数据对象列表
* @param list
*/
public Page setList(List list) {
this.list = list;
initialize();
return this;
}
/**
* 获取查询排序字符串
* @return
*/
@JsonIgnore
public String getOrderBy() {
// SQL过滤,防止注入
String reg = "(?:')|(?:--)|(/\\*(?:.|[\\n\\r])*?\\*/)|"
+ "(\\b(select|update|and|or|delete|insert|trancate|char|into|substr|ascii|declare|exec|count|master|into|drop|execute)\\b)";
Pattern sqlPattern = Pattern.compile(reg, Pattern.CASE_INSENSITIVE);
if (sqlPattern.matcher(orderBy).find()) {
return "";
}
return orderBy;
}
/**
* 设置查询排序,标准查询有效, 实例: updatedate desc, name asc
*/
public void setOrderBy(String orderBy) {
this.orderBy = orderBy;
}
/**
* @return fields 字段属性查询,拼接用,分隔
*/
@JsonIgnore
public String getFields() {
return fields;
}
/**
* @param fields 要设置的 fields
*/
public void setFields(String fields) {
this.fields = fields;
}
/**
* 获取点击页码调用的js函数名称
* function ${page.funcName}(pageNo){location="${ctx}/list-${category.id}${urlSuffix}?pageNo="+i;}
* @return
*/
@JsonIgnore
public String getFuncName() {
return funcName;
}
/**
* 设置点击页码调用的js函数名称,默认为page,在一页有多个分页对象时使用。
* @param funcName 默认为page
*/
public void setFuncName(String funcName) {
this.funcName = funcName;
}
/**
* 获取分页函数的附加参数
* @return
*/
@JsonIgnore
public String getFuncParam() {
return funcParam;
}
/**
* 设置分页函数的附加参数
* @return
*/
public void setFuncParam(String funcParam) {
this.funcParam = funcParam;
}
/**
* 设置提示消息,显示在“共n条”之后
* @param message
*/
public void setMessage(String message) {
this.message = message;
}
/**
* 分页是否有效
* @return this.pageSize==-1
*/
@JsonIgnore
public boolean isDisabled() {
return this.pageSize==-1;
}
/**
* 是否进行总数统计
* @return this.count==-1
*/
@JsonIgnore
public boolean isNotCount() {
return this.count==-1;
}
/**
* 获取 Hibernate FirstResult
*/
@JsonIgnore
public int getFirstResult(){
int firstResult = (getPageNo() - 1) * getPageSize();
if (firstResult >= getCount()) {
firstResult = 0;
}
return firstResult;
}
/**
* 获取 Hibernate MaxResults
*/
@JsonIgnore
public int getMaxResults(){
return getPageSize();
}
/**
* @Title: getFiledsSql
* @Description: 将fields的属性名称替换为字段名称
* @param @param mapName
* @param @param fileds
* @param @return
* @param @throws Exception
* @return Map 返回类型
* @author (DDM)
* @version V1.0
*/
@JsonIgnore
public String getFiledsSql(String mapName,String fileds) throws Exception{
String[] fieldsColoumn=null;
String orderByStr="";
//所有字段名
List columnList=new ArrayList();
//所有属性名
List propertyList=new ArrayList();
//属性名称为key,字段名称为value
Map columnMap=new HashMap();
if(!StringUtil.isBlank(fileds)){
//解析Fileds的字段/属性名称
fieldsColoumn=fileds.split(",");
//从resultMap中获取字段名称和属性名称
if(fieldsColoumn != null){
SqlSessionFactory sqlSessionFactory=SpringContextHolder.getBean(SqlSessionFactory.class);
ResultMap map= sqlSessionFactory.getConfiguration().getResultMap(mapName+"Map");
List mapping= map.getResultMappings();
for(ResultMapping mapp:mapping){
columnList.add(mapp.getColumn().toLowerCase());
propertyList.add(mapp.getProperty());
columnMap.put(mapp.getProperty(), mapp.getColumn());
}
}
if(fieldsColoumn != null){
fileds="";
for (String column : fieldsColoumn) {
if(!StringUtil.isBlank(column)){
column=column.trim();
if(columnList.contains(column.toLowerCase())){
fileds+=","+column;
}else if(propertyList.contains(column)){
fileds+=","+columnMap.get(column).toString();
}
}
}
if(!StringUtil.isBlank(fileds)){
fileds=fileds.substring(1);
}
}
}
return fileds;
}
/**
* @Title: getOrderBySql
* @Description: 将orderBy的属性名称替换为字段名称
* @param @param mapName
* @param @param orderBy
* @param @return
* @param @throws Exception
* @return Map 返回类型
* @author (DDM)
* @version V1.0
*/
@JsonIgnore
public static String getOrderBySql(String mapName,String orderBy) throws Exception{
String[] orderByColoumn=null;
//所有字段名
List columnList=new ArrayList();
//所有属性名
List propertyList=new ArrayList();
Map columnMap=new HashMap();
if(!StringUtil.isBlank(orderBy)){
//解析orderBy的字段/属性名称
orderByColoumn=orderBy.split(",");
//从resultMap中获取字段名称和属性名称
if(orderByColoumn != null){
SqlSessionFactory sqlSessionFactory=SpringContextHolder.getBean(SqlSessionFactory.class);
ResultMap map= sqlSessionFactory.getConfiguration().getResultMap(mapName+"Map");
List mapping= map.getResultMappings();
for(ResultMapping mapp:mapping){
columnList.add(mapp.getColumn().toLowerCase());
propertyList.add(mapp.getProperty());
columnMap.put(mapp.getProperty(), mapp.getColumn());
}
}
if(orderByColoumn != null){
orderBy="";
for (String column : orderByColoumn) {
if(!StringUtil.isBlank(column)){
if(columnList.contains(replaceOrderBy(column))){
orderBy+=","+column;
}else if(propertyList.contains(replaceOrderBy(column))){
//如果是实体类名字则获取对应数据库名字+排序方式
orderBy+=","+columnMap.get(replaceOrderBy(column)).toString()
+column.replace(replaceOrderBy(column), "");
}
}
}
if(!StringUtil.isBlank(orderBy)){
orderBy=orderBy.substring(1);
}
}
}
return orderBy;
}
/**
* @Title: replaceOrderBy
* @Description: 去掉orderBy中的desc和asc
* @param @param str
* @param @return
* @return Map 返回类型
* @author (DDM)
* @version V1.0
*/
public static String replaceOrderBy(String str){
if(!StringUtil.isBlank(str)){
str=str.trim();
str=str.replace(" asc","");
str=str.replace(" ASC","");
str=str.replace(" DESC","");
str=str.replace(" desc","");
str=str.trim();
}
return str;
}
}