五;一個簡單的小demo演示分頁效果,
1,新建PageControllerTag.java
Copy上面第一步的代碼:
2,編寫標籤文件luojspage.tld
Copy上面第二步的代碼:
3,調用分頁
(1) 查詢數據的方法(這裏用的hibernate的hql語句進行查詢)
public List getPage(final String sql, int pageId, final int pageSize) {
System.out.println("yo wcomecome you 1");
final int firstId = (pageId - 1) * pageSize;
Query query = this.getHibernateTemplate().getSessionFactory()
.getCurrentSession().createQuery(sql);
query.setFirstResult(firstId);
query.setMaxResults(pageSize);
List list = query.list();
return list;
}
(2) 在action或servlet中調用查詢數據的方法
int pageSize = 3; //設置每頁要顯示的條數
request.setAttribute("pageSize", new Integer(pageSize));
String pageNo = request.getParameter("pageNo");// 獲取當前頁號
if (pageNo == null)
pageNo = "1";
int pagenum = Integer.parseInt(pageNo); //
// 利用這兩參數進行數據查詢
List listUser = user.getPage("from User", pagenum, pageSize);
//獲取中的記錄數
int size = user.serverSearchById(0, 0).size();
request.setAttribute("total", size + ""); //總條數
request.setAttribute("listUser", listUser);
return mapping.findForward("succ");
4,頁面代碼
<%@ page language="java" pageEncoding="gbk"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://www.luojs.cn" prefix="luojs"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>分頁測試</title>
</head>
<body>
<h2>This is my Struts page. </h2><br>
<h4>Worcome ${name } <a href="longin.do?path=toadds">add User</a></h4> <hr/>
<table width="650px" border="1" background="#fffff" align="center" cellpadding="0" cellspacing="0" bordercolor="#cccfff" bgcolor="#ffffff">
<caption>
User info
</caption>
<tr bgcolor="#99ffcc">
<th scope="col">id</th>
<th scope="col">UserName</th>
<th scope="col">PassWord</th>
<th scope="col">Update</th>
<th scope="col">Del</th>
</tr>
<c:forEach items="${listUser}" var="user">
<tr>
<td>${user.id }</td>
<td>${user.username}</td>
<td>${user.password }</td>
<td> <a href="longin.do?path=toupdate&id=${user.id }">update</a> </td>
<td> <a href="longin.do?path=del&id=${user.id }" onClick="return(confirm(' delete this is user?'));">delete</a> </td>
</tr>
</c:forEach>
</table>
<table border="0" align="center"><tr><td>
<luojs:pageTag pageSize="${requestScope.pageSize}" gotoURI="longin.do?path=index"/>
</td></tr></table>
</body>
</html>
5,頁面效果: