在查询较多数据的时候我们经常会用到分页查询,在浏览器页面上将查询的结果一页一页的分开展示给我们,下面是我写的一个使用pageInfo工具来完成简单的分页功能的步骤以及代码:
1.首先是在我们的service层对dao层查询出的数据进行分页操作:
1.1先在service接口中添加上 pageNum,pageSize 这两个参数,代表页数以及每页条数,该函数的返回结果改为PageInfo<>:
public PageInfo<Students> getStuAll(Integer timeteach,Integer pageNum,Integer pageSize);
1.2在service的实现类中加上 PageHelper.startPage(pageNum,pageSize);这句代码,然后把查询出来的集合放进 PageInfo 中并返回
@Override
public PageInfo<Students> getStuAll(Integer timeteach,Integer pageNum,Integer pageSize) {
PageHelper.startPage(pageNum,pageSize);
List<Students> list = teachMainDao.selectStuAll(timeteach,cnamecid,stuname);
return new PageInfo<Students>(list);
}
2.接下来是在controller层接收返回结果,在这里也需要添加上 pageNum,pageSize 这两个参数,但是在这里可以通过@RequestParam() 注解设置这两个参数不是必须的并且修改默认值,在函数里面把从service层接收的 PageInfo 集合存到request作用域中:
@RequestMapping("tostushow")
public String stushow(String timeteach,HttpServletRequest req,
@RequestParam(required=false,defaultValue="1") Integer pageNum,
@RequestParam(required=false,defaultValue="3") Integer pageSize){
PageInfo<Students> pg = teachMainService.getStuAll(timeteach,pageNum,pageSize);
req.setAttribute("pg", pg);
return "stushow";
}
3.在前端页面接收传过来的集合遍历输出,这里要注意的一点是,如果是遍历pageInfo类型的集合,要使用它里面的自带的 .list 这个属性来代表集合然后遍历输出
<#list pg.list as tsl>
<tr>
<td>${tsl_index+1}</td>
<td>${tsl.stuname}</td>
<td>${tsl.stunum}</td>
<td>${tsl.stusex}</td>
<td>${tsl.stuage}</td>
<td>${tsl.clz.cname}</td>
<td>${tsl.stuhome}</td>
<td>${tsl.sturemarks}</td>
<td>头像缩略图,点击放大</td>
</tr>
</#list>
4.上一页与下一页功能的实现,设置上页下页的超链接按钮,点击的时候跳转到相应请求并且带上 pageNum 这个参数,并且上页下页要对 pageNum 这个参数的值进行+1或者-1的操作,这样就实现了分页查询的功能:
<#if pg.hasPreviousPage>
<a href="/tostushow?pageNum=${pg.pageNum-1}">上一页</a>
</#if>
<#if pg.hasNextPage>
<a href="/tostushow?pageNum=${pg.pageNum+1}">下一页</a>
</#if>