效果图
1. pom.xml 添加PageHelp的jar包
<!-- 引入Mybatis分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.5</version>
</dependency>
2. mybatis-config.xml文件中注册mybatis分页插件
<!-- mybatis分页插件 -->
<plugins>
<plugin interceptor="com.github.pagehelper.PageHelper"></plugin>
</plugins>
**提示:**如果没有这个配置文件,则新建一个,复制下面全部代码粘贴即可,然后将这个文件放在
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- mybatis分页插件 -->
<plugins>
<plugin interceptor="com.github.pagehelper.PageHelper"></plugin>
</plugins>
</configuration>
然后在applicationContext.xml文件中添加扫描新建的配置文件。
<!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 自动扫描mapping.xml文件 -->
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
<property name="mapperLocations" value="classpath:com/crm/sys/**/mapper/*.xml"></property>
</bean>
3. Controller层写插件获得所有用户的方法
/**
* 分页查询用户信息
* @param pn 默认从第一页开始 请求参数
* @param model
* @return
*/
@RequestMapping("customerInfo")
public String getCustomers(@RequestParam(value="pn", defaultValue="1")Integer pn, Model model){
// 从第一条开始 每页查询五条数据
PageHelper.startPage(pn, 5);
List<Customer> customers = customerService.getAllCustomer();
// 将用户信息放入PageInfo对象里
PageInfo<Customer> page = new PageInfo<Customer>(customers, 5);
model.addAttribute("pageInfo", page);
return "index";
}
**4. jsp页面遍历的数据变成 pageInfo.list **
**5. jsp页面添加分页信息 **
<!-- 分页信息 -->
<div class="row">
<!-- 分页文字信息,其中分页信息都封装在pageInfo中 -->
<div class="col-md-6">
当前第:${pageInfo.pageNum }页,总共:${pageInfo.pages }页,总共:${pageInfo.total }条记录
</div>
<!-- 分页条 -->
<div class="col-md-6">
<nav aria-label="Page navigation">
<ul class="pagination">
<li><a href="${ctx }/customer/customerInfo?pn=1">首页</a></li>
<c:if test="${pageInfo.hasPreviousPage }">
<li>
<a href="${ctx }/customer/customerInfo?pn=${pageInfo.pageNum-1 }" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
</c:if>
<c:forEach items="${pageInfo.navigatepageNums }" var="page_Num">
<c:if test="${page_Num == pageInfo.pageNum }">
<li class="active"><a href="#">${page_Num }</a></li>
</c:if>
<c:if test="${page_Num != pageInfo.pageNum }">
<li><a href="${ctx }/customer/customerInfo?pn=${page_Num }">${page_Num }</a></li>
</c:if>
</c:forEach>
<c:if test="${pageInfo.hasNextPage }">
<li>
<a href="${ctx }/customer/customerInfo?pn=${pageInfo.pageNum+1}" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</c:if>
<li><a href="${ctx }/customer/customerInfo?pn=${pageInfo.pages}">末页</a></li>
</ul>
</nav>
</div>
<!-- 分页条结束 -->
</div>