public class SplitPage {
//分頁請求時,請求標識參數
final public static String FIRSTPAGE="first";//請求第壹頁
final public static String PREVIOUSEPAGE="previous";//請求上壹頁
final public static String NEXTPAGE="next";//請求下壹頁
final public static String LASTPAGE="last";//請求最後壹頁
private int pageRows=10;//每頁顯示記錄數,默認10條,可以在頁面設置
private int totalRows=0;//總的記錄數,這個參數由NoteDAO對象提供
private int currentPage=1;//當前顯示的頁面編號,默認第壹頁
private int firstPage=1;//首頁位置,默認第壹頁
private int totalPages=1;//總的頁面數量,默認就壹頁
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getFirstPage() {
return firstPage;
}
public void setFirstPage(int firstPage) {
this.firstPage = firstPage;
}
public int getPageRows() {
return pageRows;
}
public void setPageRows(int pageRows) {
if(pageRows==0)throw new ArithmeticException();
this.pageRows = pageRows;//如果pageRows被設置為零,應當拋出異常.
//修改每頁顯示記錄數,將會直接影響總頁面數,所以要同時修改
this.totalPages=(this.totalRows%this.pageRows==0)?this.totalRows/this.pageRows:this.totalRows/this.pageRows+1;
}
public int getTotalRows() {
return totalRows;
}
//設置分頁對象的總記錄屬性後,就應該根據每頁面顯示記錄數,計算得到總的頁面數
public void setTotalRows(int totalRows) {
this.totalRows = totalRows;
//計算總的頁面數(或最後的頁面號),兩個整數相除如果剛好除盡,值就是相除後的商,否則如果有余數,商應當還加1.
this.totalPages=(this.totalRows%this.pageRows==0)?this.totalRows/this.pageRows:this.totalRows/this.pageRows+1;
}
//不應該提供方法設置總頁面數,它是計算得到的
//但應當提供獲取總頁面數的方法.
public int getTotalPages() {
return totalPages;
}
//根據請求頁面的標識參數,重新計算當前要顯示的頁面
//核心方法,實現分頁顯示功能.
public int confirmPage(String flag){
int newPage=this.currentPage;
if(flag!=null){//flag只可能是下面值之壹
if(flag.equals(SplitPage.FIRSTPAGE)){
newPage=1;
}else if(flag.equals(SplitPage.LASTPAGE)){
newPage=this.totalPages;
}else if(flag.equals(SplitPage.NEXTPAGE)){
//頁面總數和當前頁面編號相等嗎,如果是那麽頁面編號不往後走,否則頁面編號加壹
newPage=(this.totalPages==this.currentPage)?this.currentPage:this.currentPage+1;
}else if(flag.equals(SplitPage.PREVIOUSEPAGE)){
//第壹個頁面和當前頁面相等嗎,如果是那麽頁面編號不往前走,否則頁面編號減壹
newPage=(this.firstPage==this.currentPage)?this.currentPage:this.currentPage-1;
}else{//否則是壹個數字字符串
int tpage=Integer.parseInt(flag.trim());
newPage=tpage;
}
}else{//如果請求標識參數為空,那麽當前頁碼不變
newPage=this.currentPage;
}
//在返回前設置當前頁面
this.setCurrentPage(newPage);
return newPage;
}
}