想获取源码请关注公众号:ASSUE
回复 ”0628“
在上一篇博客的基础上进一步开发,在展示全部用户的页面上实现分页。
首先导jar包,在ssm_web目录下的pom.xml文件中添加代码,导入pagehelper包
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.2</version>
</dependency>
修改IUserService接口代码,在findAll()函数下添加:
public List<UserInfo> findAll(int page,int size);
基于上条改变,改动UserServicel类下的findAll函数:
public List<UserInfo> findAll(int page,int size) {
PageHelper.startPage(page,size); //提醒page在显示哪一页的数据和要显示多少条数据
return userDao.findAll();
}
在UserController下修改findAll函数:
@RequestMapping("findAll.do")
//给page、size设置默认参数
public ModelAndView findAll(@RequestParam(defaultValue = "1") int page,@RequestParam(defaultValue = "5")int size){
ModelAndView mv=new ModelAndView();
List<UserInfo> infos=userService.findAll(page,size);
PageInfo pageInfo=new PageInfo(infos);
mv.addObject("pageInfo",pageInfo);
mv.setViewName("user-list");
return mv;
}
修改user-list,jsp文件中关于页数显示的代码为:设置每页四条数据
</div>
<!-- /.box-body -->
<div class="box-tools pull-right">
<ul class="pagination">
<li><a href="${pageContext.request.contextPath}/user/findAll.do?page=1&size=4" aria-label="Previous">首页</a></li>
<li><a href="${pageContext.request.contextPath}/user/findAll.do?page=${pageInfo.pageNum-1}&size=4">上一页</a></li>
<c:forEach begin="1" end="${pageInfo.pages}" var="pageNum">
<li><a href="${pageContext.request.contextPath}/user/findAll.do?page=${pageNum}&size=4">${pageNum}</a></li>
</c:forEach>
<li><a href="${pageContext.request.contextPath}/user/findAll.do?page=${pageInfo.pageNum+1}&size=4">下一页</a></li>
<li><a href="${pageContext.request.contextPath}/user/findAll.do?page=${pageInfo.pages}&size=4" aria-label="Next">尾页</a></li>
</ul>
</div>
</div>
<!-- /.box-footer-->
要告诉数据库分页,需在applicationContext.xml下的sqlSessionFactory处添加:
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageInterceptor">
<property name="properties">
<props>
<prop key="helperDialect">mysql</prop>
<prop key="reasonable">true</prop>
</props>
</property>
</bean>
</array>
</property>
运行程序: