使用pageHelper进行分页
*maven项目在pom.xml中导入maven依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>最新版本</version>
</dependency>
- 在 MyBatis 配置 xml 中配置拦截器插件
<plugins>
<!-- com.github.pagehelper为PageHelper类所在包名 -->
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<!-- 使用下面的方式配置参数,后面会有所有的参数介绍 -->
<property name="param1" value="value1"/>
</plugin>
</plugins>
- 在spring中配置拦截器的插件
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注意其他配置 -->
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageInterceptor">
<property name="properties">
<!--使用下面的方式配置参数,一行配置一个 -->
<value>
params=value1
</value>
</property>
</bean>
</array>
</property>
</bean>
- Controller层的代码
//获取数据库中的所有数据
@RequestMapping(value = "/getList", method = RequestMethod.GET)
public String getStudentList(ModelMap map, @RequestParam(defaultValue = "1", required = true, value = "pageNo") Integer pageNo) throws Exception {
//设置每页的记录数
Integer pageSize = 2;
//分页查询
PageHelper.startPage(pageNo, pageSize);
//查询所有的学生信息
List<Student> students = studentService.getList();
PageInfo<Student> pageInfo = new PageInfo<Student>(students);
map.addAttribute("pageInfo", pageInfo);
return "/student/studentGetList";
}
- 对应的jsp页面
<center>
<p>当前${pageInfo.pageNum}页,总${pageInfo.pages}页,总${pageInfo.total}条记录</p>
<a href="${pageContext.request.contextPath}/getList?pageNo=${pageInfo.firstPage}">第一页</a>
<c:if test="${pageInfo.hasPreviousPage}">
<a href="${pageContext.request.contextPath}/getList?pageNo=${pageInfo.pageNum-1}">上一页</a>
</c:if>
<c:if test="${pageInfo.hasNextPage}">
<a href="${pageContext.request.contextPath}/getList?pageNo=${pageInfo.pageNum+1}">下一页</a>
</c:if>
<a href="${pageContext.request.contextPath}/getList?pageNo=${pageInfo.lastPage}">最后页</a>
</center>