自定義標籤分頁

爲了管理分頁,包括條件查詢分頁。用一個自定義標籤方式,是一個很好的方案。

NewPage.java  定義一個分頁類

package com.oa.util.newpage;
import java.util.List;
/**
 *
 * @author geQ
 * 分頁類
 * @param <T>
 */
    public class NewPage<T> {
        //需要獲取參數有:  每頁條數,當前頁,總條數
        private int pageSize;//每頁條數
        private int firstPage = 1;//首頁
        private int previousPage;//上一頁
        private int currentPage;//當前頁
        private int nextPage;//下一頁
        private int lastPage;//尾頁
        private int pageCount;//總頁數
        private int totalCount;//總條數
        private List<T> list;//只用來存放當前頁要現實的數據內容記錄
        //一鍵設置其他參數...
        public void setOthers(){
            //計算總頁數   pageCount
            this.pageCount = (this.totalCount-1)/this.pageSize+1;
            //下一頁
            if((this.currentPage+1)<=this.pageCount){
                this.nextPage = this.currentPage+1;
            }else{
                this.nextPage = this.currentPage;
            }
            //上一頁
            if(this.currentPage>1){
                this.previousPage = this.currentPage-1;
            }else{
                this.previousPage = this.currentPage;
            }
            //設置尾頁
            this.lastPage = this.pageCount;
        }
        //快捷設置初始化參數,也可以用其他單個的設置,參數依次爲:當前頁,每頁條數,總條數
        public void setFast(int currentPage,int pageSize,int total){
            this.currentPage = currentPage;
            this.pageSize = pageSize;
            this.totalCount = total;
            setOthers();
        }
        public int getPageSize() {
            return pageSize;
        }
        public void setPageSize(int pageSize) {
            this.pageSize = pageSize;
        }
        public int getFirstPage() {
            return firstPage;
        }
        public void setFirstPage(int firstPage) {
            this.firstPage = firstPage;
        }
        public int getPreviousPage() {
            return previousPage;
        }
        public void setPreviousPage(int previousPage) {
            this.previousPage = previousPage;
        }
        public int getCurrentPage() {
            return currentPage;
        }
        public void setCurrentPage(int currentPage) {
            this.currentPage = currentPage;
        }
        public int getNextPage() {
            return nextPage;
        }
        public void setNextPage(int nextPage) {
            this.nextPage = nextPage;
        }
        public int getLastPage() {
            return lastPage;
        }
        public void setLastPage(int lastPage) {
            this.lastPage = lastPage;
        }
        public int getPageCount() {
            return pageCount;
        }
        public void setPageCount(int pageCount) {
            this.pageCount = pageCount;
        }
        public int getTotalCount() {
            return totalCount;
        }
        public void setTotalCount(int totalCount) {
            this.totalCount = totalCount;
        }
        public List<T> getList() {
            return list;
        }
        public void setList(List<T> list) {
            this.list = list;
        }
    }

定義一個標籤核心類PagerTag.java

package com.oa.util.newpage;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
public class PagerTag extends TagSupport{
    /**
     *
     */
    private static final long serialVersionUID = 1L;
    private String url;//請求的action
    private int pageSize;//每頁的條數
    private int currentPage;//當前頁
    private int pageCount;//總頁數
    private int totalCount;//總條數
    private String param;//接受參數的鍵數組
                                                            
    public String getParam() {
        return param;
    }
    public void setParam(String param) {
        this.param = param;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    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 getPageCount() {
        return pageCount;
    }
    public void setPageCount(int pageCount) {
        this.pageCount = pageCount;
    }
    public int getTotalCount() {
        return totalCount;
    }
    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
    }
    public int doEndTag() throws JspException{
        return this.EVAL_PAGE;
    }
    public int doStartTag() throws JspException{
        HttpServletRequest request = (HttpServletRequest)pageContext.getRequest();
        String path = request.getSession().getServletContext().getRealPath("\\");
        JspWriter jw = pageContext.getOut();
        StringBuilder sb = new StringBuilder();//拼寫輸出的HTML文本
        sb.append("<div style='display:none'>\r\n")
          .append("<form action='"+url+"' method='post' id='myFormPageTag'>\r\n")
          .append("<input type='text' name='pageSize' id=\"_pageSize\" value=''/>\r\n")//將得到的每頁條數記入form
          .append("<input type='text' name='currentPage' id=\"_current\" value=''/>\r\n")//將得到的當前頁記入form
          .append("<input type='text' name='pageCount' id=\"_pageCount\" value='"+pageCount+"'/>\r\n")//將得到的總頁數記入form
          .append("<input type='text' name='totalCount' id=\"_totalCount\" value='"+totalCount+"'/>\r\n");//將得到的總條數記入form
        if(param!=null){
            String [] keyValue = param.split(";");
            for (int i = 0,len=keyValue.length; i < len; i++) {
                if(!keyValue[i].equals("")){
                    if(keyValue[i].split("=").length==1){
                        sb.append("<input type='text' name='"+keyValue[i].split("=")[0]+"' value=''/>\r\n");//將參數循環記入form
                    }else{
                        sb.append("<input type='text' name='"+keyValue[i].split("=")[0]+"' value='"+keyValue[i].split("=")[1]+"'/>\r\n");//將參數循環記入form
                    }
                }
            }
        }
        sb.append("</form></div>\r\n");
        /*
         * 分頁代碼的html文本
         *
         */
        System.out.println();
        //顯示首頁
        sb.append("<a href=\"javascript:submitMyPage('"+pageSize+"','"+1+"')\">首頁</a>\r\n");
        //如果當前頁大於1,輸出前頁文本
        if(this.currentPage>1)
            sb.append("<a href=\"javascript:submitMyPage('"+pageSize+"','"+(this.currentPage-1)+"')\">前頁</a>\r\n");
        //從當前頁前兩頁開始顯示
        if(this.currentPage-2>0)
            sb.append("<a href=\"javascript:submitMyPage('"+pageSize+"','"+(this.currentPage-2)+"')\">"+(this.currentPage-2)+"</a>\r\n");
        //當前頁前一頁
        if(this.currentPage>1)
            sb.append("<a href=\"javascript:submitMyPage('"+pageSize+"','"+(this.currentPage-1)+"')\">"+(this.currentPage-1)+"</a>\r\n");
        //當前頁
        sb.append("<a href=\"javascript:submitMyPage('"+pageSize+"','"+(this.currentPage)+"')\"><font color='red'>"+(this.currentPage)+"</font></a>\r\n");
        //當前頁的 後頁大於總頁數時顯示
        if(this.currentPage+1<=pageCount)
            sb.append("<a href=\"javascript:submitMyPage('"+pageSize+"','"+(this.currentPage+1)+"')\">"+(this.currentPage+1)+"</a>\r\n");
        //當前頁的 後兩頁大於總頁數時顯示
        if(this.currentPage+2<=pageCount)
            sb.append("<a href=\"javascript:submitMyPage('"+pageSize+"','"+(this.currentPage+2)+"')\">"+(this.currentPage+2)+"</a>\r\n");
        //當前頁+1大於總頁數時顯示
        if(this.currentPage+1<=pageCount)
            sb.append("<a href=\"javascript:submitMyPage('"+pageSize+"','"+(this.currentPage+1)+"')\">後頁</a>\r\n");
        //顯示尾頁
        sb.append("<a href=\"javascript:submitMyPage('"+pageSize+"','"+pageCount+"')\">尾頁</a>\r\n");
        sb.append("<span class='zt1'>每頁<span class=\"bai\">")
          .append("<select onchange=\"selectPagesize(this)\" id=\"pageSize\">\r\n");
        for (int i = 5; i <=50; i+=5) {
            sb.append("<option value='"+i+"'>"+i+"</option>\r\n");
        }
        sb.append("</select></span>條&nbsp;\r\n")
          .append("共"+pageCount+"頁&nbsp;共"+totalCount+"條\r\n")
          .append("跳轉到<img src=\"page\\pageImage\\control_start.png\" width=\"16\" height=\"16\"  border=\"0\"/>\r\n")
          .append("<input type=\"text\" value=\""+currentPage+"\" style=\"width:20\" size=\"2\" id=\"current\"/>\r\n")
          .append("<img src=\".\\page\\pageImage\\control_end.png\" width=\"16\" border=\"0\" height=\"16\"           .append("<img src=\".\\page\\pageImage\\Shortkey.png\" width=\"16\" height=\"16\" title=\"go\"  border=\"0\"/>\r\n")
          .append("</span>");
        /*
         * 對分頁的css樣式控制
         */
        sb.append("<style type=\"text/css\">\r\n");
        sb.append("a:LINK {\r\n"+
            "color: #000000;\r\n"+
            "}\r\n"+
            "a:VISITED {\r\n"+
            "color: #000000;\r\n"+
            "}\r\n"+
            "a{\r\n"+
            "cursor: pointer;\r\n"+
            "text-decoration: none\r\n"+
            "}\r\n" +
            ".zt1{\r\n"+
            "font-size: 14px; \r\n"+
            "color: #333333; \r\n" +
            "font-style:微軟雅黑"+
            "} \r\n" +
            ".bai{\r\n"+
            "font-size: 12px;\r\n" +
            "line-height: 20px;\r\n"+
            "color: #333333;\r\n"+
            "}\r\n");
        sb.append("</style>\r\n");
        /*
         * 對分頁的js控制
         * $submitMyPage方法進行頁面跳轉
         * selectPagesize方法進行每頁條數的選擇
         * jump方法進行頁面的靜態調整
         * go方法跳轉所輸入頁面
         */
        sb.append("<script language=\"javascript\" src=\""+path+"page\\jquery-1.7.2.min.js\"></script>\r\n");
        sb.append("<script language=\"javascript\">\r\n");
        sb.append("function submitMyPage(pageSize,currentPage){\r\n" +
          "$('#_pageSize').val(pageSize);\r\n"+    
          "$('#_current').val(currentPage);\r\n"+
          "document.getElementById('myFormPageTag').submit();\r\n"+
          "}\r\n"+   
        "function selectPagesize(obj){\r\n"+   
          "$('#_pageSize').val(obj.value);\r\n" +
          "document.getElementById('myFormPageTag').submit();\r\n"+ 
          "}\r\n"+
        "function jump(num,pageCount){\r\n"+         
                  "var currentNum = $(\"#current\").val();\r\n"+     
                  "   $(\"#current\").val(parseInt(currentNum, 10)+parseInt(num, 10));\r\n"+
                  "   if($(\"#current\").val()<=1){\r\n"+
                  "       $(\"#current\").val(1);\r\n"+
                  "   }\r\n"+
                  "   if($(\"#current\").val()>=pageCount){\r\n"+
                  "       $(\"#current\").val(pageCount);\r\n"+
                  "   }\r\n"+
                  "}\r\n"+
        "function go(pageSize){\r\n" +
            "$('#_pageSize').val(pageSize);\r\n"+
            "$('#_current').val($(\"#current\").val());\r\n"+
            "document.getElementById('myFormPageTag').submit();\r\n"+
           "}\r\n" +
        "window. +
            "$('#pageSize').val("+pageSize+");\r\n" +
           "}\r\n" +
          "");
        sb.append("</script>");
        try {
            jw.print(sb.toString());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return this.SKIP_BODY;
    }
}

寫一個pageTag.tld文件,將文件放到web-inf下

<?xml version="1.0" encoding="utf-8"?>
<taglib version="2.0" xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd">
    <tlib-version>1.0</tlib-version>
    <short-name>p</short-name>
    <uri>http://pagetld</uri>
    <tag>
        <name>page</name>
        <tag-class>com.oa.util.newpage.PagerTag</tag-class>
        <body-content>empty</body-content>
        <attribute>
            <name>url</name>
            <required>true</required>
            <rtexprvalue>true</rtexprvalue>
            <type>java.lang.String</type>
        </attribute>
        <attribute>
            <name>pageSize</name>
            <required>true</required>
            <rtexprvalue>true</rtexprvalue>
            <type>java.lang.Integer</type>
        </attribute>
        <attribute>
            <name>currentPage</name>
            <required>true</required>
            <rtexprvalue>true</rtexprvalue>
            <type>java.lang.Integer</type>
        </attribute>
        <attribute>
            <name>pageCount</name>
            <required>true</required>
            <rtexprvalue>true</rtexprvalue>
            <type>java.lang.Integer</type>
        </attribute>
        <attribute>
            <name>totalCount</name>
            <required>true</required>
            <rtexprvalue>true</rtexprvalue>
            <type>java.lang.Integer</type>
        </attribute>
        <attribute>
            <name>param</name>
            <required>false</required>
            <rtexprvalue>true</rtexprvalue>
            <type>java.lang.String</type>
        </attribute>
    </tag>
</taglib>

定義一個分頁dao

package com.oa.dao.newPage.daoImp;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.oa.dao.newPage.daoInter.NewPageDaoInter;
import com.oa.util.newpage.NewPage;
/**
 * A data access object (DAO) providing persistence and search support for
 * PersonnelContract entities. Transaction control of the save(), update() and
 * delete() operations can directly support Spring container-managed
 * transactions or they can be augmented to handle user-managed Spring
 * transactions. Each of these methods provides additional information for how
 * to configure it for the desired type of transaction control.
 *
 * @see com.oa.model.zz.PersonnelContract
 * @author MyEclipse Persistence Tools
 * @param <T>
 */
@SuppressWarnings("unchecked")
public class NewPageDao<T> extends HibernateDaoSupport implements NewPageDaoInter{
    private static final Logger log = LoggerFactory
            .getLogger(NewPageDao.class);
                        
    public List<T> findBySql(String sql) {
        Session session = this.getHibernateTemplate().getSessionFactory().openSession();
        List<T> list = session.createQuery(sql).list();
        return list;
    }
/*
* 查詢以及分頁
*/
    public long totalCount(String sql){
        List<Long> list = getHibernateTemplate().find(sql);
        return list.get(0);
    }
    public NewPage<T> findAll(String sql1,String sql2,String currentPage,String pageSize){
        int totalNum = (int)totalCount(sql1);
        Session session = this.getHibernateTemplate().getSessionFactory().openSession();
        NewPage<T> page = new NewPage<T>();
        if(currentPage==null||currentPage.equals("")){
            currentPage = "1";
        }
        if(pageSize==null||pageSize.equals("")){
            pageSize = "10";
        }
        Transaction tx = session.beginTransaction();
        page.setFast(Integer.parseInt(currentPage), Integer.parseInt(pageSize), totalNum);
        Query query = session.createQuery(sql2);
        query.setFirstResult((Integer.parseInt(currentPage)-1)*Integer.parseInt(pageSize));
        query.setMaxResults(Integer.parseInt(pageSize));
        page.setList((List<T>)query.list());
        tx.commit();
        session.close();
        return page;
    }
}

導入jq庫文件

使用說明:

1、將 pageTag.tld 文件放到web-inf下。

2、newPage爲封裝好的baseDao.其中包含了dao的接口與實現。將此文件根據個人情況放入src下即可。

3、將page文件夾放到webroot下即可。裏邊主要是分頁的圖片以及jquery庫文件

4、NewPage.java是對分頁的具體的封裝。根據個人情況放入src下的包即可。

5、PagerTag.java是分頁的核心文件,將此文件放入工程下的src/com/oa/util/newpage即可。

剛導入工程可能有個別文件報錯,將文件中對類的引用的包進行修改即可。

最後在jsp頁面上面導入標籤:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>這個是c標籤

<%@ taglib prefix="p" uri="http://pagetld" %>這個爲自定義的分頁標籤


在你需要分頁的地方寫上標籤:

<p:page totalCount="${page.totalCount}" pageSize="${page.pageSize}" pageCount="${page.pageCount}" url="${url}" currentPage="${page.currentPage}"/>

此標籤需要 在action傳參數:總條數:totalCount,每頁條數:pageSize,需要跳轉的action;url.當前頁:currentPage,總頁數:pageCount,

如果需要條件查詢:在標籤內加入param屬性:例如

<p:page totalCount="${page.totalCount}" pageSize="${page.pageSize}" pageCount="${page.pageCount}" url="${url}" currentPage="${page.currentPage}" param="name=zhangsan;age=14"/>

以key=value;key=value進行傳值。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章