程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> 自定義分頁標簽

自定義分頁標簽

編輯:關於JAVA

近期在做的S2SH項目,因為多處用到分頁,BOSS要求小弟將其抽象出來。小弟不才,實際參與開發的經驗也就1年。

於是花了點時間將其做成自定義標簽供所有需要分頁的業務調用。小結一下,供新手參考

自定義標簽使用如下:

JSP頁面引入:

<%@ taglib uri="/htdz-tag" prefix="htdz-tag"%>

在需要擺放翻頁的相關按鈕處使用:

<htdz-tag:PagerTag pagesize="${pagesize}" rowcount="${rowcount}" currpagenum="${currpagenum}" action="${action}"/>

以下介紹如何自定義標簽:

1.首先是針對自定義標簽的描述:

創建WEB-INF/tags/htdz-tag.tld標簽描述文件:

<?xml version="1.0" encoding="UTF-8" ?>
<taglib 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"
version="2.0">
<description>htdz tag</description>
<display-name>htdz tag</display-name>
<tlib-version>1.0</tlib-version>
<short-name>htdz-tag</short-name>
<uri>/htdz-tag</uri>

<tag>
<!--分頁控件使用說明:
1.最全參數用法:<htdz-tag:PagerTag pagesize="${pagesize}" rowcount="${rowcount}" currpagenum="${currpagenum}" action="${action}" className="button_small"/>
1.最簡參數用法:<htdz-tag:PagerTag pagesize="${pagesize}" rowcount="${rowcount}" currpagenum="${currpagenum}" action="${action}"/>
參數說明:
1. pagesize為每頁記錄數(必寫)
2. rowcount為總記錄數(必寫)
3. currpagenum為當前頁數(必寫)
4. className為分頁按鈕樣式,如果不寫,則為默認樣式
5. action為URL請求路徑(必寫)
-->
<description>分頁控件</description>
<!--JSP裡使用時的標簽名-->
<name>PagerTag</name>
<!--用以將自定義標簽解析成控件的Java類-->
<tag-class>com.htdz.util.tag.PagerTag</tag-class>
<body-content>JSP</body-content>
<!--每個attribute代表標簽的一個屬性-->
<attribute>
<description>pagesize:每頁條數</description>
<!--屬性名-->
<name>pagesize</name>
<!--是否必填屬性-->
<required>true</required>
<!--此屬性值是否接受EL,<%= 之類的形式-->
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>rowcount:總記錄數</description>
<name>rowcount</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>currpagenum:當前頁數</description>
<name>currpagenum</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>action:URL請求路徑</description>
<name>action</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>className:用於客戶端確定分頁按鈕的樣式</description>
<name>className</name>
<required>false</required>
</attribute>
</tag>

</taglib>

2.創建用於將標簽解析為頁面翻頁控件的類

PagerTag.java

public class PagerTag extends TagSupport {
    public static final int USER_PAGESIZE = 5;// 禮品搜索--每頁記錄數
    private static final String DEFAULT_BUTTON_CLASS= "button_small"; //翻頁按鈕默認樣式
    private static final String DISABLE_BUTTON_CLASS= "button_small_disable"; //失效按鈕默認樣式
    private int pagesize;
    private int rowcount;
    private int currpagenum;
    private String action;
    private String className; 
    public PagerTag() {
    }
    public void setPagesize(int pagesize) {
        this.pagesize = pagesize;
    }
    public void setRowcount(int rowcount) {
        this.rowcount = rowcount;
    }
   public void setCurrpagenum(int currpagenum) {
        this.currpagenum = currpagenum;
    }
    public void setClassName(String className) {
        this.className = className;
    }
    public void setAction(String action) {
        this.action = action;
    }
    public int doStartTag() throws JspException {
        if (new Integer(pagesize) == null) {
            throw new JspException("PagerTag標簽中缺乏pagesize屬性!");
        }else if(pagesize==0){
            throw new JspException("PagerTag標簽中的pagesize屬性無值!");
        }
        if (new Integer(rowcount) == null) {
            throw new JspException("PagerTag標簽中缺乏rowcount屬性!");
        }
        if (new Integer(currpagenum) == null) {
            throw new JspException("PagerTag標簽中缺乏currpagenum屬性!");
        }
        if (action == null) {
            throw new JspException("PagerTag標簽中缺乏action屬性!");
        }else if(action.length()==0){
            throw new JspException("PagerTag標簽中的action屬性無值!");
        }
        //如果頁面標簽中沒寫className屬性,則讓翻頁按鈕應用默認的按鈕樣式
        if(className==null||className.length()==0){
            className = DEFAULT_BUTTON_CLASS;
        }
        //獲取總頁數
        int totalpagesize = getTotalpagesize(rowcount);
        //用以標志是否能上翻
        boolean noUp = false;
        //用以標志是否能下翻
        boolean noDown = false;
        //聲明應用於'首頁','上一頁'按鈕的樣式(因為此倆按鈕要麼同時失效,要麼同時可用)
        String buttonClass1 = className;
        //聲明應用於'下一頁','尾頁'按鈕的樣式(同上)
        String buttonClass2 = className;
        //如果無記錄,則設置總頁數與當前頁數都為1
        if(rowcount==0){
            currpagenum = 1;
            totalpagesize = 1;
        }
        //如果當前頁是第一頁
        if(currpagenum==1){
            noUp = true;
            //設置'首頁','上一頁'按鈕失效樣式
            buttonClass1 = DISABLE_BUTTON_CLASS;
        }
        //如果當前頁是最大頁
        if(currpagenum==totalpagesize){
            noDown = true;
            //設置'下一頁','尾頁'按鈕失效樣式
            buttonClass2 = DISABLE_BUTTON_CLASS;
        }
        try {
            StringBuffer html = new StringBuffer();
            html.append(currpagenum+"/"+totalpagesize+"頁");
            html.append("<input class="+buttonClass1+" type=\"button\" value=\"首頁\" onclick=\"turnPage('first','"+currpagenum+"','"+totalpagesize+"','"+action+"')\" ");
            if(noUp){
                html.append("disabled=\"true\"");
            }
            html.append("/>");
            html.append("<input class="+buttonClass1+" type=\"button\" value=\"上一頁\" onclick=\"turnPage('up','"+currpagenum+"','"+totalpagesize+"','"+action+"')\" ");
            if(noUp){
                html.append("disabled=\"true\"");
            }
            html.append("/>");
            html.append("<input class="+buttonClass2+" type=\"button\" value=\"下一頁\" onclick=\"turnPage('down','"+currpagenum+"','"+totalpagesize+"','"+action+"')\"");
            if(noDown){
                html.append("disabled=\"true\"");
            }
            html.append("/>");
            html.append("<input class="+buttonClass2+" type=\"button\" value=\"尾頁\" onclick=\"turnPage('last','"+currpagenum+"','"+totalpagesize+"','"+action+"')\" ");
            if(noDown){
                html.append("disabled=\"true\"");
            }
            html.append("/>");
            html.append(currpagenum+"/"+totalpagesize+"頁&nbsp;&nbsp;");
            html.append("<input type=\"text\" maxlength=\"3\" id=\"text\" size=\"3\" onkeypress=\"return checkInput(event);\" />頁");
            html.append("<input class="+className+" type=\"button\" value=\"GO\" onclick=\"turnPage('to','"+currpagenum+"','"+totalpagesize+"','"+action+"')\" />");
            pageContext.getOut().println(html.toString());
        } catch (Exception e) {
            throw new JspException(e.getMessage());
        }
         return this.SKIP_BODY;
    }
     /**
      * 根據總記錄數得到總頁數
      * 
      * @param rowcount
      *            總記錄數
      * @return 總頁數
      */
    public int getTotalpagesize(int rowcount) {
        int totalpagesize = 0;
        if (rowcount % pagesize == 0) {
            totalpagesize = rowcount / pagesize;
        } else {
            totalpagesize = rowcount / pagesize + 1;
        }
        return totalpagesize;
    }
}

到此為止,自定義標簽書已完成。可應用於項目各處,只要頁面上遵循標簽描述規則,後台該給標簽屬性傳值的時候記得傳就行了。

以下用一個簡單的例子來說明一下,紅色字體顯示的部分別忘記寫就行了。

UserAction.java:

public class UserAction extends ActionSupport {

private UserService userService;
private List<User> users;

public String findUser(){
String str = null;
HttpServletRequest request = ServletActionContext.getRequest();
Map sessionMap = ActionContext.getContext().getSession();

String currpagenum= "1";
try {
String pagenum = request.getParameter("pagenum ");
if(pagenum != null && pagenum .length()!=0){
currpagenum= pagenum ;
}
} catch (Exception e) {

}

//查詢用戶記錄
users= userService.findUser(pageNum);
if(users.size!=0){
request.setAttribute("users", users);

int rowcount = userService.getCount();

request.setAttribute("rowcount ",rowcount );
request.setAttribute("currpagenum",currpagenum);

str = "success";//成功視圖
}else{
message = "無記錄!"
str = "failure";//失敗視圖
}

request.setAttribute("pagesize", PagerTag.USER_PAGESIZE);
request.setAttribute("action", "findUser.action);

//返回視圖
return str;
}

public UserService getUserService() {
return userService;
}
public void setUserService(UserService userService) {
this.userService = userService;
}

public List<User> getUsers(){
return users;
}
public void setUsers(List<User> users){
this.users = users;
}

}

UserService.java:

public class UserService {

private UserDao userDao;

public List<User> findUser(String pageNum){
List<User> userList = userDao.findUser(pageNum);
return userList;
}

public int getCount(){
int count = userDao.getCount();
return count;
}

public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
}

UserDao.java:

public class UserDao extends HibernateDaoSupport {

/**
* 查詢用戶
* @return User對象集合
*/
public List<User> findUser(String pagenum) {
List<User> users = null;
Session session = null;
try {
int myPagenum= Integer.parseInt(pagenum);
String hql = "from User";
session = this.getSession();
Query query = session.createQuery(hql);
query.setFirstResult(Pager.USER_PAGESIZE * (myPagenum - 1));
query.setMaxResults(Pager.USER_PAGESIZE);
users = query.list();
session.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (session != null) {
session.close();
}
}
return users;
}

/**
* 獲取用戶總記錄數
* @return 用戶總記錄數
*/
public int getCount(){
String hql ="select count(id) from User";
Session session = null;
int count =0;
try {
session = this.getSession();
Query query = session.createQuery(hql);
List list = query.list();
session.flush();
count = Integer.parseInt(list.get(0).toString());
} catch (Exception e) {
e.printStackTrace();
} finally{
session.close();
}
return count;
}

}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved