日常工作項目裡,分頁是十分常見的,網上也有大把的分頁插件,性能和美觀程度都比較不錯,但是有時候並不一定能滿足我們的需求,因為大部分的分頁插件都是在客戶端分頁,有的甚至需要你一次性查詢出所有的數據放入內存,在內存進行分頁,而且分也時,只是單純分頁只接受頁碼,並不能傳入本頁的某些參數到另一個頁面做重新查詢的條件,進而重新分頁。www.2cto.com 根據jsp自定義分頁標簽的特性,我們可以定制自己的分頁標簽,更加方便開發中的使用,關於jsp的自定義標簽,上篇已有詳細的介紹說明, 該頁最下面的 分頁欄,即是自定義的jsp的標簽,我這裡給的名字是<page:page pager="${requestScope.pb}" />,即只要引入它即可出現該分頁欄,由於為了方便,樣式可能不太好看,這個大家可以自己去調節。 下面我們開始實現這個page標簽,首先新建一個web項目,並引入struts必要地幾個jar包。新建一個包,取名為com.page.util,將page的三個實現類放在下面,分別是Pager.java,PagerHelp.java,PageTag.java,它們的實現分別如下: Pager.java: Java代碼 /** * 保存分頁信息的類 * * */ public class Pager { private int totalRows; // 總行數 private int pageSize = 10; // 每頁顯示的行數 private int currentPage; // 當前頁號 private int totalPages; // 總頁數 private int startRow; // 當前頁在數據庫中的起始行 private String linkUrl; // 要跳轉的URL public Pager() { } public Pager(int _totalRows) { totalRows = _totalRows; totalPages = totalRows / pageSize; int mod = totalRows % pageSize; if (mod > 0) { totalPages++; } currentPage = 1; startRow = 0; } /** * 設定查詢的起始行數 * * @param currentPage */ public void setStart(int currentPage) { this.currentPage = currentPage; startRow = (currentPage - 1) * pageSize; } public int getTotalRows() { return totalRows; } public void setTotalRows(int totalRows) { this.totalRows = totalRows; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public int getTotalPages() { return totalPages; } public void setTotalPages(int totalPages) { this.totalPages = totalPages; } public int getStartRow() { return startRow; } public void setStartRow(int startRow) { this.startRow = startRow; } public String getLinkUrl() { return linkUrl; } public void setLinkUrl(String linkUrl) { this.linkUrl = linkUrl; } } PagerHelp.java: Java代碼 import javax.servlet.http.HttpServletRequest; /** * 控制分頁的類 * * */ public class PagerHelper { public static Pager getPager(HttpServletRequest req, int totalRows) { // 定義pager對象,用於傳到頁面 Pager pager = new Pager(totalRows); // 從Request對象中獲取當前頁號 String currentPage = req.getParameter("cpage"); // 如果當前頁號為空,表示為首次查詢該頁 // 如果不為空,則刷新pager對象,輸入當前頁號等信息 if (currentPage != null) { pager.setStart(Integer.parseInt(currentPage)); } else { pager.setStart(1); } return pager; } } PageTag.java: Java代碼 import java.io.IOException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.TagSupport; /** * 標簽類 用於分頁查詢 * */ public class PageTag extends TagSupport { /** * */ private static final long serialVersionUID = 1L; private Pager pager; @SuppressWarnings("static-access") public int doStartTag() { ////標簽開始時調用的方法 try { JspWriter out = pageContext.getOut(); if(pager==null){ out.print("沒有記錄"); out.flush(); return super.SKIP_BODY; } out.print("第 " + pager.getCurrentPage() + " 頁/共 " + (pager.getTotalPages()) + " 頁"); if (pager.getCurrentPage() == 1) { out.print("[最首頁]"); out.print("[上一頁]"); } if (pager.getCurrentPage() != 1) { out.print("[<a href='" + pager.getLinkUrl() + "?cpage=1'>最首頁</a>]"); out.print("[<a href='" + pager.getLinkUrl() + "?cpage=" + (pager.getCurrentPage() - 1) + "'>上一頁</a>]"); } for (int i = pager.getCurrentPage() - 3; i <= pager .getCurrentPage() + 3; i++) { if (i <= 0 || i > pager.getTotalPages()) { continue; } if (i == pager.getCurrentPage()) { out .print("[<span style='color:#FF0000; border: 1px solid #cccccc; font-weight:bold; width:15px;text-align: center;'> " + i + " </span>]"); } else { out.print("[<a href='" + pager.getLinkUrl() + "?cpage=" + i + "'> " + i + " </a>]"); } } if (pager.getCurrentPage() == pager.getTotalPages() || pager.getTotalPages() == 0) { out.print("[下一頁]"); out.print("[最末頁]"); } if (pager.getCurrentPage() != pager.getTotalPages() && pager.getTotalPages() != 0) { out.print("[<a href='" + pager.getLinkUrl() + "?cpage=" + (pager.getCurrentPage() + 1) + "'>下一頁</a>]"); out.print("[<a href='" + pager.getLinkUrl() + "?cpage=" + (pager.getTotalPages()) + "'>最末頁</a>]"); } out.flush(); } catch (IOException ex) { ex.printStackTrace(); } return super.SKIP_BODY;//表示不顯示標簽間的文字 } @SuppressWarnings("static-access") public int doEndTag() { //標簽結束時調用的方法 return super.EVAL_PAGE;//表示JSP頁面繼續運行 } public void setPager(Pager pager) { this.pager = pager; } public Pager getPager() { return pager; } } 實現類的完成即是為了實現標簽的功能,這裡我們在WEB-INF下新建文件夾mytag,新建文件pagetag.tld,在這個文件裡對你想要聲明的自定義標簽,並制定它的實現類,代碼如下: Tld代碼 <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd"> <taglib xmlns="http://java.sun.com/JSP/TagLibraryDescriptor"> <tlib-version>1.0</tlib-version> <jsp-version>1.2</jsp-version> <short-name>My Tags</short-name> <tag> <name>page</name> <tag-class>com.page.util.PageTag</tag-class> <body-content>empty</body-content> <attribute> <name>pager</name> <required>true</required> <rtexprvalue>true</rtexprvalue> <type>com.page.util.Pager</type> </attribute> </tag> </taglib> 至此,我們的自定義page分頁標簽業已全部實現了,下面我們就來模擬使用下,新建com.action.TestAction.java,代碼如下: Java代碼 import java.util.ArrayList; import java.util.List; import com.bean.TestBean; import com.util.Pager; import com.util.PagerHelper; public class TestAction extends BaseAction { private static final long serialVersionUID = 5293541447709620793L; private List<TestBean> bList; @Override public String execute() throws Exception { bList=new ArrayList<TestBean>(); for (int i = 0; i < 100; i++) { bList.add(new TestBean(Long.parseLong(String.valueOf(i)), "person"+i, i+10+"歲", i+"@qq.com")); } int totalRow=bList.size(); Pager pager=null; pager = PagerHelper.getPager(request, totalRow); // 初始化分頁對象 pager.setLinkUrl(request.getRequestURI()); // 設置跳轉路徑 request.setAttribute("pb", pager); // 將分頁信息保存在Request對象 //模擬分頁時,是要傳遞參數,模擬傳入a,b。單純分頁時,則不需要該段的4行代碼 StringBuffer urlParam = new StringBuffer(); urlParam.append("&a="+100); urlParam.append("&b="+200); request.setAttribute("urlParam", urlParam.toString()); bList=bList.subList(pager.getStartRow(),pager.getStartRow()+10); return SUCCESS; } public List<TestBean> getbList() { return bList; } public void setbList(List<TestBean> bList) { this.bList = bList; } } 這個類模擬了數十條的分頁數據,下面新建兩個jsp頁面,代碼分頁如下: index.jsp: Jsp代碼 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <a href="test.action">Test Go~~</a> </body> </html> test.jsp: Jsp代碼 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <%@ taglib prefix="page" uri="../WEB-INF/config/mytag/pagetag.tld" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <script type="text/javascript" src="../js/Pager.js"></script> </head> <body> <div style="margin-left: 110px;"> <table> <tr> <th colspan="4" ><p style="font-family: sans-serif;font-size: 20px">測試分頁</p></th> </tr> <tr> <td width="80px">ID</td> <td width="80px">Name</td> <td width="80px">Age</td> <td width="80px">Email</td> </tr> <s:iterator value="bList"> <tr> <td width="80px"><s:property value="tId"/> </td> <td width="80px"><s:property value="tName"/> </td> <td width="80px"><s:property value="tAge"/> </td> <td width="80px"><s:property value="tEmail"/> </td> </tr> </s:iterator> </table> </div> <p style="margin-left: 17px"> <page:page pager="${requestScope.pb}" /> </p> </body> <script> Pager.setUrlParam("${urlParam}"); </script> </html> 這個頁面會使用到page標簽,及在文件頭引入所需的taglib,並引入Pager.js,該js的代碼如下: Js代碼 /** * 分頁操作對象 */ var Pager = function(){ return{ setUrlParam: function(param) { //為翻頁標簽鏈接增加顯示flag參數 var obj=$(".pagerTarge > a");//獲得分頁標簽下的所有<a> //alert(obj.length); if(obj!=null && obj.length>0) { for(var i=0;i<obj.length;i++) { var tempUrl=$(obj[i]).attr('href'); //添加flag $(obj[i]).attr('href',tempUrl+param); } } } } }(); 至此,在web.xml和struts.xml中做好各項配置,啟動服務器,鍵入localhost:8080/mytag/index.jsp,點擊"Test Go~~"鏈接,即出現截圖效果,如有報錯,請根據錯誤檢查各項配置。 如果需要在分頁時,在頁面間傳遞參數,如以上action代碼中模擬的a和b的話,即全部用stringbuffer拼接就可以了,我們右鍵test.jsp效果頁面時,可以看到傳遞的參數url,如圖: