一:编写实体类
@Setter
@Getter
@ToString
@Entity
@Repository
public class PageBean {
private Integer currPage;//当前页
private Integer pageSize;//每页条数
private Integer totalCount;//总条数
private Integer totalPage;//总页数
private List list;//当前页数据
}
二:编写dao层,写sql语句(mysql)
//查询总条数
@Select("select count(1) from product")
public Integer findByTotalCount();
//分页查询
@Select("select * from (SELECT *,(@rowNum:=@rowNum+1) as rowNo FROM product,(Select (@rowNum :=0) ) b) " +
"res where rowNo>=#{param1} and rowNo<=#{param2}")
List findByProduct(Integer start,Integer end);
三:编写service层以及实现类
1、service层
public PageBean findByProduct(Integer currPage, Integer pageSize);
2、实现类
@Override
public PageBean findByProduct(Integer currPage, Integer pageSize) {
//1、创建PageBean对象
PageBean pageBean = new PageBean<>();
//2、获取当前页面(页面传参过来)
pageBean.setCurrPage(currPage);
//3、每页条数
pageBean.setPageSize(pageSize);
//4、总条数
Integer totalCount = productDao.findByTotalCount();
pageBean.setTotalCount(totalCount);
//5、总页数
double ceil = Math.ceil(totalCount * 1.0 / pageSize);
pageBean.setTotalPage((int) ceil);
//6、当前页面数据,从数据库查询
int start = pageSize * (currPage - 1) + 1;
int end = pageSize * currPage;
List productList = productDao.findByProduct(start, end);
pageBean.setList(productList);
return pageBean;
}
四、编写控制器
//分页查询
@RequestMapping("/findByProduct")
public ModelAndView findByProduct(@RequestParam(value = "currPage",required = false,defaultValue = "1") Integer currPage,
@RequestParam(value = "pagesSize",required = false,defaultValue = "5") Integer pageSize){
PageBean pageBean = new PageBean<>();
pageBean =productService.findByProduct(currPage, pageSize);
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("pageBean",pageBean);
modelAndView.setViewName("product-list");
return modelAndView;
}
五、编写web网页文件
总共${pageBean.totalPage}页,共${pageBean.totalCount} 条数据。 每页
2
3
5
10
条
- 首页
- 上一页
- ${i}
- 下一页
- 尾页
$("#pageSize option[value=${pageBean.pageSize}]").prop("selected","selected");
function gotoPage(currPage) {
// 获取每页显示条数
var pageSize = $("#pageSize").val();
if(currPage<1){
return;
}
if(currPage>${pageBean.totalPage}){
return;
}
location.href="${pageContext.request.contextPath}/product/findByProduct?currPage="+currPage+"&pageSize="+pageSize
;
}