分页功能
首页不进行分页会显示所有数据,因此分页,每页显示5条数据
首页查询数据时,SQL语句添加 LIMIT 限制,根据页码获取数据
-
FruitDAOImpl 调用父类 BaseDAO 的 executeQuery 方法时,传入的SQL语句结构使用 LIMIT 限制,将页码作为占位符参数传入
-
@Override public List<Fruit> getFruitList(Integer pageNo) { return super.executeQuery("select * from t_fruit LIMIT ?, 5", (pageNo-1)*5); }
-
-
IndexServlet 通过 fruitDAO 对象的 .getFruitList(pageNo) 方法将 pageNo 传给 FruitDAOImpl
-
//默认第一页为首页 Integer pageNo = 1; //从请求中获取最新 pageNo,非空时,更改 pageNo String pageNoStr = request.getParameter("pageNo"); if(StringUtil.isNotEmpty(pageNoStr)){ pageNo = Integer.parseInt(pageNoStr); } List<Fruit> fruitList = fruitDAO.getFruitList(pageNo);
-
在首页添加分页按钮,绑定分页功能
<div style="width:60%;margin-left:20%;border:0px solid red;padding-top:4px;" class="center">
<input type="button" value="首 页" class="btn" th:onclick="" th:disabled=""/>
<input type="button" value="上一页" class="btn" th:onclick="" th:disabled=""/>
<input type="button" value="下一页" class="btn" th:onclick="" th:disabled=""/>
<input type="button" value="尾 页" class="btn" th:onclick="" th:disabled=""/>
</div>
-
点击事件实现页码跳转,需要知道当前页的 pageNo ,也就是说要使得在 html 页面也能读到 pageNo,实现方式:将 pageNo 保存到 session 会话保存域中,使用 thymeleaf 在 html 标签中就能读到 pageNo
-
session.setAttribute("pageNo", pageNo);
-
-
在 html 页面直接使用 session 会话保存域中的 pageNo,通过 js 中的方法,将新 pageNo 传入 js 方法中,在 js 方法中请求新的页面。
-
上一页:session.pageNo + 1,下一页:session.pageNo - 1
-
<div style="width:60%;margin-left:20%;border:0px solid red;padding-top:4px;" class="center"> <input type="button" value="首 页" class="btn" th:onclick="|page(1)|" th:disabled=""/> <input type="button" value="上一页" class="btn" th:onclick="|page(${session.pageNo - 1})|" th:disabled=""/> <input type="button" value="下一页" class="btn" th:onclick="|page(${session.pageNo + 1})|" th:disabled=""/> <input type="button" value="尾 页" class="btn" th:onclick="" th:disabled=""/> </div>
-
function page(pageNo){ window.location.href="index?pageNo="+pageNo; }
-
-
要实现跳转到尾页,需要知道一共有多少页,则需要知道一共有几条数据
-
在 FruitDAO 中添加 查询总记录条数的方法,在 FruitDAOImpl 中实现该方法
-
@Override public int getFruitCount(){ return ((Long) super.executeComplexQuery("select count(*) from t_fruit")[0]).intValue(); }
-
-
在 IndexServlet 中获取到总记录条数,计算出总页数,将总页数存在 session 中,从而在 html 的尾页跳转中使用总页数进行跳转
-
int fruitCount = fruitDAO.getFruitCount(); //计算总记录条数与页数的关系 session.setAttribute("pageCount", (fruitCount+5-1)/5);
-
<input type="button" value="尾 页" class="btn" th:onclick="|page(${session.pageCount})|" th:disabled=""/>
-
当前为第一页时,首页按钮和上一页按钮不可用;当前为最后一页时,尾页按钮和下一页按钮不可用;
-
判断当前页面,使用 disable 让 input 按钮失效
-
首 页 th:disabled="${session.pageNo == 1}"/> 上一页 th:disabled="${session.pageNo == 1}"/> 下一页 th:disabled="${session.pageNo == session.pageCount}"/> 尾 页 th:disabled="${session.pageNo == session.pageCount}"/>