1.在pom中添加如下代码。
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.2</version>
</dependency>
2.我使用的是SSM框架所以要在配置文件中添加相关配置。
2.1 applicationContext.xml
<!--分页-->
<bean id="pageHelper" class="com.github.pagehelper.PageHelper"/>
2.2 mybatis-config.xml
<!--分页-->
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
</plugin>
</plugins>
3.现在控制类中能引用PageHelper了
3.1先添加个注解
@Autowired
PageHelper pageHelper;
3.2 上代码
@RequestMapping("/examAdminIndex")
public String examAdminIndex(@RequestParam(value="pn",defaultValue="1") Integer pn, HttpSession session) {
int pageSize=6;/*每页的有几条数据*/
pageHelper.startPage(pn, pageSize);
List<Subject> subjects=examService.findAllSubject();/*查询的数据*/
PageInfo pageInfo=new PageInfo(subjects);
session.setAttribute("PageInfo",pageInfo);
return "adminIndex/examAdminIndex";
}
4.jsp页面,前后端交互用session
4.1控制分页的跳转
<script type="text/javascript">
$(function(){//控制分页的跳转
$("#li"+${sessionScope.PageInfo.pageNum}).addClass("active");
$("#previous").click(function(){
if(${sessionScope.PageInfo.isFirstPage}){
alert("当前为第一页,没有上一页了");
return false;
}
});
$("#next").click(function(){
if(${sessionScope.PageInfo.isLastPage}){
alert("当前为最后一页,没有下一页了");
return false;
}
});
});
</script>
4.2底部的页面跳转栏
<div id="div2">总共有${sessionScope.PageInfo.pages}页${sessionScope.PageInfo.total}条记录,当前为第${sessionScope.PageInfo.pageNum}页</div>
<div id="div3">
<nav aria-label="...">
<ul class="pagination">
<li ><a href="/examAdminIndex?pn=${PageInfo.pageNum-1}" aria-label="Previous" id="previous"><span aria-hidden="true">«</span></a></li>
<li><a href="/examAdminIndex">首页</a></li>
<c:forEach begin="1" end="${PageInfo.pages}" var="id">
<li id="li${id}"><a href="/examAdminIndex?pn=${id}">${id}</a></li>
</c:forEach>
<li><a href="/examAdminIndex?pn=${PageInfo.pages}">尾页</a></li>
<li><a href="/examAdminIndex?pn=${PageInfo.pageNum+1}" aria-label="Next"><span aria-hidden="true" id="next">»</span></a></li>
</ul>
</nav>
</div>
</div>