1.构建pageInfo分页类,定义相关属性
2.重写findAll,实现模糊查找方法。
<select id="findAll" resultType="user">
select * from tb_user
<if test="username!=null and username!=''">
where username like concat("%",#{username},"%")
</if>
limit #{start},5
</select>
@Override
public PageInfo<User> findAll(int currentPage, String username) {
PageInfo<User> pageInfo = new PageInfo<>();
pageInfo.setSize(5);
//tc为查询数据的总行数
int tc = userDao.getTotalCount(username);
pageInfo.setTotalCount(tc);
//tp为总行数
int tp = (int)Math.ceil(tc/5.0);
pageInfo.setTotalPage(tp);
//翻页判断
if (currentPage<1){
pageInfo.setCurrentPage(1);
}else if (currentPage>tp){
pageInfo.setCurrentPage(tp);
}else {
pageInfo.setCurrentPage(currentPage);
}
//0,5,10,15.....
int start = (pageInfo.getCurrentPage()-1)*5;
List<User> userList = userDao.findAll(start, username);
pageInfo.setList(userList);
return pageInfo;
}
在controller层注册新的findAll方法
@RequestMapping("/findAll.do")
public ModelAndView findAll(@RequestParam(defaultValue = "1")int currentPage, String username,
@RequestParam(defaultValue = "0")int type, HttpSession session){
if (type==1){
session.setAttribute("searchName",username);
}else {
username=(String) session.getAttribute("searchName");
}
PageInfo<User> pageInfo = userService.findAll(currentPage, username);
ModelAndView mv = new ModelAndView();
mv.addObject("pageInfo",pageInfo);
mv.setViewName("user-list");
return mv;
}
实现获取信息总条数方法,添加接口
<select id="getTotalCount" resultType="int">
select count(*) from tb_user
<if test="username!=null and username!= '' ">
where username like concat("%",#{username},"%")
</if>
</select>
3.在user-list界面添加上下页跳转功能
<div class="box-tools pull-right">
<ul class="pagination">
<li><a href="/user/findAll.do" aria-lable="Previous">首页</a> </li>
<li><a href="/user/findAll.do?currentPage=${pageInfo.currentPage-1}">上一页</a> </li>
<c:forEach begin="1" end="${pageInfo.totalPage}" var="pageNum">
<li><a href="/user/findAll.do?currentPage=${pageNum}"></a> </li>
</c:forEach>
<li><a href="/user/findAll.do?currentPage=${pageInfo.currentPage+1}">下一页</a> </li>
<li><a href="/user/findAll.do?currentPage=${pageInfo.totalPage}" aria-lable="Next">尾页</a> </li>
</ul>
</div>
4.实现分页和搜索功能
(1)分页
(2)搜索