PageHelper是基於攔截器實現的myBatis分頁插件
PageHelper的Github主頁 : https://github.com/pagehelper/Mybatis-PageHelper
一.通過maven引入PageHelper的jar包
<dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.1.8</version> </dependency>
二.在myBatis配置文件中配置PageHelper
<plugins> <!-- com.github.pagehelper為PageHelper類所在包名 --> <plugin interceptor="com.github.pagehelper.PageInterceptor"> <!-- 使用下面的方式配置參數,后面會有所有的參數介紹 --> <property name="helperDialect" value="mysql"/> </plugin> </plugins>
也可以在spring中配置PageHelper,具體步驟請參考PageHelper的Github主頁官方教程
三.在Controller層使用PageHelper實現分頁查詢
/**
* 分頁查詢練習
* @param mav
* @param currentPage 當前頁數
* @return
*/
@RequestMapping("/pagination")
public ModelAndView queryUsers(ModelAndView mav, Integer currentPage){
//緊挨在查詢語句前調用PageHelper的startPage(int pageNum, int pageSize)方法,否則分頁查詢不生效
PageHelper.startPage(currentPage, 5);
//查詢用戶
List<User> users = ts.queryUsers();
//用PageInfo包裝List查詢結果,查看PageInfo源碼,了解更多
PageInfo<User> pi = new PageInfo<User>(users);
mav.addObject("pageInfo", pi);
mav.setViewName("test/paginationTest");
return mav;
}
四.JSP頁面的書寫方法
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>PageHelper分頁查詢</title>
</head>
<body>
<!-- 點擊查詢 -->
<a href="${pageContext.request.contextPath }/test/pagination?currentPage=1">查詢</a>
<!-- 有上一頁的時候顯示上一頁 -->
<c:if test="${pageInfo.hasPreviousPage }">
<a href="${pageContext.request.contextPath }/test/pagination?currentPage=${pageInfo.prePage}">上一頁</a>
</c:if>
<!-- 有下一頁的時候顯示下一頁 -->
<c:if test="${pageInfo.hasNextPage }">
<a href="${pageContext.request.contextPath }/test/pagination?currentPage=${pageInfo.nextPage}">下一頁</a>
</c:if>
<!-- 遍歷查詢結果 -->
<!-- 注意! 在EL表達式中,用.list即可調用pageInfo中封裝的list對象 -->
<c:forEach items="${pageInfo.list }" var="u" >
<p>${u.username } + ${u.realname }</p>
</c:forEach>
<br/>當前頁:${pageInfo.pageNum }
<br/>總頁數:${pageInfo.pages }
<br/>當前頁面第一個元素在數據庫中的行號:${pageInfo.startRow }
<br/>當前頁面最后一個元素在數據庫中的行號:${pageInfo.endRow }
</body>
</html>
五.其他
重點了解PageInfo類,可以自行查閱源碼
關於更詳細的內容(更多的配置內容和使用方法等等),請參考PageHelper官方文檔
地址 : https://github.com/pagehelper/Mybatis-PageHelper/blob/master/wikis/zh/HowToUse.md
f
