如何在springMVC中实现分页功能
1.在pom.xml导入pageHelper的包
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.2.1</version>
</dependency>
2.在spring-config中开启pageHelper
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:dao/*.xml"/>
<property name="typeAliasesPackage" value="pojo"/>
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageHelper">
<property name="properties">
<value>
dialect=mysql
reasonable=true
</value>
</property>
</bean>
</array>
</property>
</bean>
3.在controller中将查到的list返回值设为PageInfo<>,并且在参数中传入pageNum参数
PageInfo<Document> pageInfo= (PageInfo<Document>) fileService.getDocu(name,fileId,pageNum);
4.在service的实现类中,添加如下代码
PageHelper.startPage(pageNum, 2);
return new PageInfo<Document>(list, 2);
//Document是实体类,list是查询得到的结果,2是pageSize
5.在jsp页面中,如下代码:
首先在jsp中,传出一个隐藏的pageNum
<input id="pageNum" name="pageNum" type="hidden">
<c:if test="${pageInfo.pages gt 1}">
<%--当前页数--%>
当前第${pageInfo.pageNum}页
<%--上一页--%>
<c:if test="${pageInfo.hasPreviousPage}"><a href="#" onclick="goPage(${pageInfo.prePage})">上一页</a></c:if>
<%--如果当前的页数与pageNum相等,颜色为红--%>
<c:forEach items="${pageInfo.navigatepageNums}" var="num">
<a href="#" onclick="goPage(${num})" style="${num eq pageInfo.pageNum?'color:red':''}">${num}</a>
</c:forEach>
<%--下一页--%>
<c:if test="${pageInfo.hasNextPage}"><a href="#" onclick="goPage(${pageInfo.nextPage})">下一页</a></c:if>
<%--跳转带指定的页--%>
跳转到<input id="goNum" size="3"><input type="button" value="GO" onclick="goPage($('#goNum').val())"/>
</c:if>
<%--实现页码跳转--%>
<script>
function goPage(pn){
if(isNaN(pn)){
return;
}
$("#pageNum").val(pn);
$("#searchForm").submit()
}
</script>