📄 pagehelper.java
字号:
package com.web.util;
import java.sql.*;
import java.util.*;
import com.common.*;
import com.common.util.Item;
import com.common.util.ReadHelper;
import com.dao.util.DbConnect;
public abstract class PageHelper {
//get pageNum data.
public Page getPage(String pageNum, int pageSize) {
long numberPerPage = pageSize;
int pNum = 1;
int currPageNum = 1;
Connection conn = null;
Statement stm = null;
ResultSet rs = null;
long rCount = 0;
ArrayList list = new ArrayList();
String sqlstr = getSqlStr();
if (pageNum == null)
pageNum = "1";
try {
pNum = (Integer.parseInt(pageNum) - 1) * (int) numberPerPage + 1;
currPageNum = Integer.parseInt(pageNum);
} catch (Exception ex) {
ex.printStackTrace();
}
try {
DbConnect db = new DbConnect();
conn=db.getConnection();
stm =
conn.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
rs = stm.executeQuery(sqlstr);
//whether pNum is great than record count.
long recordCount = this.getCount(rs);
//long recordCount = this.getCount(sqlstr);
if (recordCount < pNum)
throw new Exception("Not found more data.");
//rs.setFetchSize((int) numberPerPage);
int count = 0;
rs.absolute((int) pNum);
ResultSetMetaData rsmd = rs.getMetaData();
int colCount = rsmd.getColumnCount();
do{
Item item = new Item();
//Add a row data into item.
for (int i = 1; i <= colCount; i++) {
Object obj = rs.getObject(i);
if (rs.wasNull())
obj = "";
item.addAttribute(rsmd.getColumnName(i), obj);
}
//Add the item into arraylist.
list.add(item);
count++;
}while(count < numberPerPage && rs.next());
rCount = recordCount;
} catch (Exception ex) {
//ex.printStackTrace();
} finally {
try {
if (rs != null)
rs.close();
if (stm != null)
stm.close();
rs = null;
stm = null;
conn.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
Page pg = new Page(list, rCount, currPageNum, pageSize);
return pg;
}
protected long getCount(ResultSet rs) {
long result = 0;
try {
int pos = rs.getRow();
rs.last();
result = rs.getRow();
rs.first();
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
protected long getCount(String sqlStr) {
long result = 0;
ReadHelper rh = new ReadHelper();
Item item =
rh.getItem("SELECT COUNT(*) AS total FROM " + getTableName(sqlStr));
result = item.getLong("total");
return result;
}
public abstract String getSqlStr();
//public abstract getSqlStr(File settingsFile,String tags);
private String getTableName(String sqlStr) {
String tableName = "";
String tempStr = sqlStr.toUpperCase();
int firstPos = tempStr.indexOf("FROM");
tableName = tempStr.substring(firstPos + 4);
return tableName;
}
public static void main(String args[]) {
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -