java分页封装

java分页包装器:

/**
 * 分页包装器
 */
public abstract class PageWrapper {

	public PageWrapper() {}
	
	public PageWrapper(int perNo) {
		this.perNo = perNo;
	}
	
	public <T> T paging(int pageNo) throws Exception {
		this.pageNo = pageNo;
		totalNo = queryTotalCount();
		if (totalNo != 0) {
			return query(getStartIndex(), pageNo);
		}
		return null;
	}
	
	public abstract int queryTotalCount() throws Exception;
	
	public abstract <T> T query(int startIndex, int perNo) throws Exception;
	
	/**
	 * 查询的起始索引位置
	 * @return
	 */
	public int getStartIndex() {
		if (pageNo < 1) {
			throw new IllegalArgumentException("起始页号应当 >= 1");
		}
		return (pageNo - 1) * perNo;
	}
	
	/**
	 * 总页数。如果总记录数为 0,页数为1.
	 * @return
	 */
	public int getTotalPageNo() {
		if (perNo <= 0) {
			throw new IllegalArgumentException("每页的记录数量应当 > 0");
		}
		if (totalNo == 0) {
			return 1;
		}
		if (totalNo % perNo == 0) {
			return totalNo / perNo;
		}
		return totalNo / perNo + 1;
	}

	/**
	 * 总记录数
	 * @return
	 */
	public int getTotalNo() {
		return this.totalNo;
	}
	
	/**
	 * 每页数量
	 * @return
	 */
	public int getPerNo() {
		return this.perNo;
	}
	
	/** 总页数 */
	private int totalNo = 0;
	
	/** 页码 */
	private int pageNo = 0;
	
	/** 每页数量 */
	private int perNo = 20;
}
 

使用方式:

public class DefaultPageWrapper extends PageWrapper {
	
	public DefaultPageWrapper() {}
	
	public DefaultPageWrapper(int perNo) {
		super(perNo);
	}

	@Override
	public <T> T query(int startIndex, int perNo) throws Exception {
		return null;
	}

	@Override
	public int queryTotalCount() throws Exception {
		return 30;
	}
	
	public static void main(String[] args) {
		try {
			DefaultPageWrapper wrapper = new DefaultPageWrapper(50);
			Object obj = wrapper.paging(2);
			System.out.println(wrapper.getTotalPageNo());
			System.out.println(wrapper.getTotalNo());
			System.out.println(wrapper.getStartIndex());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}
 

 

你可能感兴趣的:(java)