1. 程式人生 > >Java分頁

Java分頁

1.編寫通用的分頁工具public class PageUtil { /*引數需要頁面傳入*/ private Integer pageSize=10;//每頁顯式多少條記錄 private Integer currentPage=1;//當前頁號 /*引數需要從資料查詢*/ private Integer allRowsAmount=0;//總記錄數 private List<?> items;//記錄集合 /*這些引數由計算得出*/ private Integer allPageAmount;//總頁數 private Integer currentPageStartRow=1;//當前頁面的開始行 private Integer currentPageEndRow;//當前頁面的結束行 private Integer firstPage=1;//首頁的頁號 private Integer lastPage;//末頁的頁號 private Integer prevPage;//上一頁頁號 private Integer nextPage;//下一頁頁號 private Integer startPageNum;//導航開始頁號 private Integer endPageNum;//導航結束頁號 private Integer maxPageAmount =10;//最多顯示多少頁 public List<Integer> showPageNums =new ArrayList<Integer>();//要顯示的頁號 public PageUtil() { super(); // TODO Auto-generated constructor stub } /*設定當前頁*/ public void setCurrentPage(int currentPage){ if(currentPage <1){ this.currentPage=1; }else{ this.currentPage=currentPage; } } /*設定每頁記錄數,預設10條*/ public void setPageSize(int pageSize) { this.pageSize = pageSize; } /*設定總記錄數*/ public void setAllRowsAmount(int allRowsAmount) { this.allRowsAmount = allRowsAmount; } /*設定分頁內容*/ public void setItems(List<?> items) { this.items = items; } /*設定導航頁數量*/ public void setMaxPageAmount(int maxPageAmount) { this.maxPageAmount = maxPageAmount; } public void calculatePage(){ //計算總頁數 if(this.allRowsAmount % this.pageSize ==0){ this.allPageAmount=this.allRowsAmount/this.pageSize; }else{ this.allPageAmount=this.allRowsAmount/this.pageSize+1; } //設定首頁 this.firstPage=1; //設定末頁 this.lastPage=this.allPageAmount; if(this.currentPage *pageSize <allRowsAmount){ this.currentPageEndRow =this.currentPage*pageSize; this.currentPageStartRow =(this.currentPage-1)*pageSize+1; }else{ this.currentPageEndRow =this.allRowsAmount; this.currentPageStartRow =(this.allPageAmount-1)*pageSize+1; if(this.currentPageStartRow <0){ this.currentPageStartRow=0; } } //設定前一頁 if(this.currentPage >1){ this.prevPage=this.currentPage-1; }else{ this.prevPage=this.currentPage; } //設定下一頁 if(this.currentPage <this.lastPage){ this.nextPage=this.currentPage+1; }else{ this.nextPage=this.lastPage; } //計算數字導航頁 startPageNum =Math.max(this.currentPage-maxPageAmount/2, firstPage); endPageNum =Math.min(startPageNum+maxPageAmount, lastPage); if(endPageNum-startPageNum <maxPageAmount){ startPageNum =Math.max(endPageNum -maxPageAmount , 1); } for(int i=startPageNum ;i<=endPageNum;i++){ showPageNums.add(i); } } //以下get方法是對外提供的方法用來獲取引數值 public Integer getPageSize() { return pageSize; } public Integer getCurrentPage() { return currentPage; } public Integer getAllRowsAmount() { return allRowsAmount; } public List<?> getItems() { return items; } public Integer getAllPageAmount() { return allPageAmount; } public Integer getCurrentPageStartRow() { return currentPageStartRow; } public Integer getCurrentPageEndRow() { return currentPageEndRow; } public Integer getFirstPage() { return firstPage; } public Integer getLastPage() { return lastPage; } public Integer getPrevPage() { return prevPage; } public Integer getNextPage() { return nextPage; } public Integer getStartPageNum() { return startPageNum; } public Integer getEndPageNum() { return endPageNum; } public Integer getMaxPageAmount() { return maxPageAmount; } public List<Integer> getShowPageNums() { return showPageNums; } @Override public String toString() { return "PageUtil [pageSize=" + pageSize + ", currentPage="
+ currentPage + ", allRowsAmount=" + allRowsAmount + ", 每頁內容items=" + items + ", allPageAmount=" + allPageAmount + ", currentPageStartRow=" + currentPageStartRow + ", currentPageEndRow=" + currentPageEndRow + ", firstPage=" + firstPage + ", lastPage=" + lastPage + ", prevPage=" + prevPage + ", nextPage=" + nextPage + ", startPageNum=" +
startPageNum + ", endPageNum=" + endPageNum + ", maxPageAmount=" + maxPageAmount + ", 頁號list=" + showPageNums + "]"; } public static void main(String[] args) { List<String> items =new ArrayList<String>(); for(int i=0;i<10;i++){ items.add("str"+i); } PageUtil pageUtil =new PageUtil(); pageUtil.setCurrentPage(1); //pageUtil.setItems(items); pageUtil.setAllRowsAmount(33); pageUtil.calculatePage(); System.out.println(pageUtil); }
} 2.servlet+c3p0+mysql實現分頁環境搭建:<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.2.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.22</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies> c3p0配置檔案:<c3p0-config> <!-- 預設配置 --> <default-config> <property name="jdbcUrl">jdbc:mysql://localhost:3306/basicjdbc?characterEncoding=utf-8</property> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="user">root</property> <property name="password"></property> <property name="initialPoolSize">3</property> <property name="maxPoolSize">6</property> <property name="maxIdleTime">1000</property> </default-config> <!-- 以下的配置用於個人需要再配置 --> <name-config name="my_config"> <property name="jdbcUrl">jdbc:mysql://localhost:3306/basicjdbc?characterEncoding=utf-8</property> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="user">root</property> <property name="password"></property> <property name="initialPoolSize">3</property> <property name="maxPoolSize">6</property> <property name="maxIdleTime">1000</property> </name-config> </c3p0-config> 使用c3p0連線池的工具類:public class DbUtil { private static DataSource dataSource=null; static{ dataSource=new ComboPooledDataSource(); } public static Connection getConnection(){ try{ return dataSource.getConnection(); }catch(SQLException e){ throw new RuntimeException(e); } } //釋放物件的連線 public static void close(Connection conn,Statement stmt,ResultSet rs){ if(rs !=null){ try{ rs.close(); }catch(SQLException e){ e.printStackTrace(); throw new RuntimeException(e); } } if(stmt !=null){ try{ stmt.close(); }catch(SQLException e){ e.printStackTrace(); throw new RuntimeException(e); } } if(conn !=null){ try{ conn.close(); }catch(SQLException e){ e.printStackTrace(); throw new RuntimeException(e); } } } public static void main(String[] args) throws Exception{ String sql="select id,username,gender from myuser limit 3,10"; Connection conn =DbUtil.getConnection(); PreparedStatement ps =conn.prepareStatement(sql); ResultSet rs =ps.executeQuery(); while(rs.next()){ String id =rs.getString("id"); String username =rs.getString("username"); String gender =rs.getString("gender"); System.out.println(id+","+username+","+gender); } DbUtil.close(conn,ps,rs); } } dao層:主要是獲取記錄的總數便於計算其他值,還有就是獲取每頁顯示的資料。public class UserDaoImpl implements IUserDao{ //從資料庫查詢記錄的總條數 public Integer getAllRowsAmount() throws Exception{ String sql="select count(*) from myuser"; Connection conn =DbUtil.getConnection(); PreparedStatement pstmt =conn.prepareStatement(sql); ResultSet rs =pstmt.executeQuery(); Integer allRowsAmount=0; if(rs.next()){ allRowsAmount =rs.getInt("count(*)"); } DbUtil.close(conn, pstmt, rs); return allRowsAmount; } //通過當前頁號查詢條件記錄 public List<User> getUserByCurrentPage(Integer currentPageStartRow, Integer pageSize) throws Exception{ String sql="select id,username,gender from myuser limit "+(currentPageStartRow-1)+","+pageSize; Connection conn =DbUtil.getConnection(); PreparedStatement pstmt =conn.prepareStatement(sql); ResultSet rs =pstmt.executeQuery(); List<User> list =new ArrayList<User>(); while(rs.next()){ User user =new User(); user.setId(rs.getInt("id")); user.setUsername(rs.getString("username")); user.setGender(rs.getString("gender")); list.add(user); } DbUtil.close(conn, pstmt, rs); return list; } public static void main(String[] args) throws Exception { UserDaoImpl userDaoImpl =new UserDaoImpl(); PageUtil pageUtil =new PageUtil(); pageUtil.setAllRowsAmount(userDaoImpl.getAllRowsAmount()); pageUtil.calculatePage(); for(User user :userDaoImpl.getUserByCurrentPage(pageUtil.getStartPageNum(), pageUtil.getPageSize())){ System.out.println(user.getId()+","+user.getUsername()+","+user.getGender()); } System.out.println(userDaoImpl.getAllRowsAmount()); } } dao介面:public interface IUserDao { public Integer getAllRowsAmount() throws Exception; public List<User> getUserByCurrentPage(Integer currentPageStartRow, Integer pageSize) throws Exception; } model類:User.java:[html] view plain copypublic class User { private int id; private String username; private String gender; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } } 頁面顯示的模型Page.java:public class Page { private Integer currentPage; private Integer prevPage; private Integer nextPage; private List<User> showUsers =new ArrayList<User