Struts2 分頁

來源:互聯網
上載者:User

寫一個分頁類,和大家一起分享

提供兩種分頁方式一種是首頁,上一頁,下一頁,尾頁,另一種是數字方式的

package com.demo.util;


import javax.servlet.http.HttpServletRequest;

/***
* 分頁操作
* 
* @author yaa
* 
*/
public class Pagnation {
// 記錄總數
private int totalRecordSize = 0;
// 頁碼總數
private int totalPageSize = 0;
// 當前頁碼
private int currentPage = 1;
// 每頁要顯示的記錄條數
private int pageSize = 20;
// 要操作的頁面的URL地址
private String pageUrl = "";
// 自訂要傳遞的參數字串
private String queryString = "";
//前面及後面要顯示的頁碼數
private int spaceSize = 5;

public int getSpaceSize() {
   return spaceSize;
}

public void setSpaceSize(int spaceSize) {
   this.spaceSize = spaceSize;
}

public int getTotalRecordSize() {
   return totalRecordSize;
}

public void setTotalRecordSize(int totalRecordSize) {
   this.totalRecordSize = totalRecordSize;
}

public int getTotalPageSize() {
   return totalPageSize;
}

public void setTotalPageSize(int totalPageSize) {
   this.totalPageSize = totalPageSize;
}

public int getCurrentPage() {
   return currentPage;
}

public void setCurrentPage(int currentPage) {
   this.currentPage = currentPage;
}

public int getPageSize() {
   return pageSize;
}

public void setPageSize(int pageSize) {
   this.pageSize = pageSize;
}

public String getPageUrl() {
   return pageUrl;
}

public void setPageUrl(String pageUrl) {
   this.pageUrl = pageUrl;
}

public String getQueryString() {
   return queryString;
}

public void setQueryString(String queryString) {
   this.queryString = queryString;
}

/**
* 構造方法
* 
* @param totalRecordSize
*            記錄總數量
* @param request
*            HttpServletRequest
*/
public Pagnation(int totalRecordSize, HttpServletRequest request) {
   this.totalRecordSize = totalRecordSize;
   if (request.getParameter("page") != null) {
    try {
     this.currentPage = Integer.parseInt(request
       .getParameter("page").toString());
    } catch (NumberFormatException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   } 
}

/**
* 構造方法
* 
* @param totalRecordSize
*            記錄總數量
* @param request
*            HttpServletRequest
* @param pageUrl
*            頁面操作的URL地址
*/
public Pagnation(int totalRecordSize, HttpServletRequest request,
    String pageUrl) {
   this.totalRecordSize = totalRecordSize;
   if (request.getParameter("page") != null) {
    try {
     this.currentPage = Integer.parseInt(request
       .getParameter("page").toString());
    } catch (NumberFormatException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
   this.pageUrl = pageUrl;
}

/***
* 擷取分頁產生的字串
* 
* @return
*/
public String getPagnationString() {
   this.totalPageSize = (int) Math.ceil(this.totalRecordSize
     / Math.floor(this.pageSize));
   if (this.currentPage < 1) {
    this.currentPage = 1;
   }
   if (this.currentPage > this.totalPageSize && this.totalPageSize != 0) {
    this.currentPage = this.totalPageSize;
   }
   // 分頁資訊產生
   String componentStr = componentRender();
   // 分頁產生
   return pageRender(componentStr);

}

/**
* 分頁資訊產生
* 
* @param sb
*/
private String pageRender(String componentStr) {
   StringBuffer sb = new StringBuffer();
   sb
     .append(
       "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"3\">")
     .append(
       "<tr><td width='20'></td><td class='zi17' align=\"right\">")
     .append(componentStr).append("</td>").append(
       "<td class='zi17' align=\"left\">").append("共有 ")
     .append(this.totalRecordSize).append(" 條記錄").append(" 共 ")
     .append(this.totalPageSize).append(" 頁").append(" 當前第 ")
     .append(this.currentPage).append(" 頁")
     .append(" <input type='text' id='pagnationNum' value='1' style='width:12px;height:12px' />").append(" <input type='button' style='width:20px;height:20px' value='go' onclick='goPage()'/>")
     .append("<td></td> </tr>").append("</table>")
    
     .append("<script type='text/javascript'>")
     .append("function goPage()")
     .append("{ tmpValue =document.getElementById('pagnationNum').value;")
     .append(" if(isNaN(tmpValue)){ document.getElementById('pagnationNum').value='1';return;}")   
     .append(" window.location.href='"+this.pageUrl+"?page='+tmpValue;")   
     .append("}")
     .append("</script>");

    
   return sb.toString();
}

/**
* 分頁產生
* 
* @param sb
*/
private String componentRender() {
   StringBuffer sb = new StringBuffer();

   // 如果當前頁碼大於1
   if (this.currentPage > 1) {

    sb.append("[<a href='" + this.pageUrl + "?page=1");
    sb.append(this.queryString);
    sb.append("' class=\"\">");
    sb.append("首頁");
    sb.append("</a>] [<a href='" + this.pageUrl + "?page=");
    sb.append(currentPage - 1);
    sb.append(this.queryString);
    sb.append("' class=\"\">");
    sb.append("前一頁");
    sb.append("</a>] ");
   } else {// 當前頁碼小於1
    sb.append("[首頁] [前一頁] ");
   }
   // 如果當前頁碼小於總頁碼
   if (this.currentPage < this.totalPageSize) {
    sb.append("<a href='" + this.pageUrl + "?page=");
    sb.append(currentPage + 1);
    sb.append(this.queryString);
    sb.append("' class=\"\">");
    sb.append("[下一頁]");
    sb.append("</a> [<a href='" + this.pageUrl + "?page=");
    sb.append(this.totalPageSize);
    sb.append(this.queryString);
    sb.append("' class=\"\">");
    sb.append("尾頁");
    sb.append("</a>] ");
   } else {// 當前頁碼大於總頁碼
    sb.append("[下一頁] [尾頁] ");
   }
   return sb.toString();
}

/// <summary>
    /// 設定分頁內容
    /// </summary>
    /// <param name="pageIndex">當前頁碼</param>
    /// <param name="pageSize">每頁顯示資訊條數</param>
    /// <param name="pageSize">當前頁面URL地址</param>
    /// <returns>分頁內容對象</returns>
    public String getNumPageString()
    {
   this.totalPageSize = (int) Math.ceil(this.totalRecordSize
     / Math.floor(this.pageSize));
   if (this.currentPage < 1) {
    this.currentPage = 1;
   }
   if (this.currentPage > this.totalPageSize && this.totalPageSize != 0) {
    this.currentPage = this.totalPageSize;
   }

        String pageFirstStr = "頁碼:";

        int preIndex = 0;
        int endIndex = 0;
        preIndex = (currentPage - spaceSize) < 1 ? 1 : currentPage - spaceSize;
        endIndex = (currentPage + spaceSize < spaceSize * 2 ? spaceSize * 2 : (currentPage + spaceSize)) > totalPageSize ? totalPageSize : currentPage + spaceSize;

        for (int i = preIndex - 1; i < endIndex; i++)
        {
            if ((i + 1) == currentPage)
            {
                pageFirstStr += "&nbsp;<b><font color='#ff0000'>" + currentPage + "</font></b>";
            }
            else
            {
                pageFirstStr += "&nbsp;<a href='" + this.pageUrl + "?page=" + (i + 1) + "" + this.queryString + "'>" + (i + 1) + "</a>";
            }
        }

        int toNum = 0;

        if (currentPage == totalPageSize)
        {
            toNum = totalRecordSize % pageSize == 0 ? pageSize : totalRecordSize % pageSize;
        }
        else
        {
            toNum = pageSize;
        }
        pageFirstStr += "&nbsp;共有" + totalRecordSize + "條記錄,每頁" + pageSize + "條,共有" + totalPageSize + "頁,當前第" + currentPage + "頁,第" + ((currentPage - 1) * pageSize + 1) + "條至第" + ((currentPage - 1) * pageSize + toNum) + "條。";
        String pageSecondStr = "&nbsp;跳轉到:<input type='text' id='page' class='input' onblur='chkNum(this)' size='3' value='1'>&nbsp;頁&nbsp;<input class='btn'          type=button value=跳轉 onclick=\"window.location.href='" + this.pageUrl + "?page='+document.getElementById('page').value+'" + this.queryString + "';\"><input type='hidden' id='totalPageSize' value='" + totalPageSize + "'>";


      
        StringBuilder sbTable = new StringBuilder();
        sbTable.append("<table id=\"pagation\" width=\"100%\"");
        sbTable.append("<tr id=\"pa\">");
        sbTable.append(pageFirstStr);
        sbTable.append("<td align=\"left\" height=\"30px\">");
        sbTable.append("</td>");
        sbTable.append("<td align=\"right\" height=\"30px\">");
        sbTable.append(pageSecondStr);
        sbTable.append("</td>");
        sbTable.append("</tr>");
        sbTable.append("</table>");
        
        return sbTable.toString();
    }
}
使用方法

在action對應的方法中加入

// 分頁操作
   Pagnation pagnation = new Pagnation(totalCount, request, url);
totalCount //資料總數

request

url //要進行分頁的地址

還有其它的一些屬性可能使用,已經在分頁類裡面有說明

pagnation.getPagnationString()//擷取分頁產生的字串

要action類中定義一個pageStr的欄位串設定set,get方法,把產生的字串裝配進去

在jsp頁面 可以使用struts2 的標籤 <s:property value="pageStr" escape="false" />即可

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.