1. 定义PageBean
为了让后台给前端返回多个数据,所以需要定义一个类
加泛型,自定义泛型,存什么数据,到时候创建PageBean再决定,这样代码就能够通用了
// 分页查询的JavaBean
public class PageBean<T> {
// 总记录数
private int totalCount;
// 当前页数据
private List<T> rows;
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public List<T> getRows() {
return rows;
}
public void setRows(List<T> rows) {
this.rows = rows;
}
}
2. Dao层
多个参数,记得加注解
/**
* 分页查询
* @param begin
* @param size
* @return
*/
@ResultMap("brandResultMap")
@Select("select * from tb_brand limit #{begin}, #{size}")
List<Brand> selectByPage(@Param("begin") int begin, @Param("size") int size);
/**
* 查询总记录数
* @return
*/
@Select("select count(*) from tb_brand ")
int selectTotalCount();
3. Service层
/**
* 分页查询
* @param currentPage 当前页码
* @param pageSize 每页展示条数
* @return
*/
PageBean<Brand> selectByPage(int currentPage,int pageSize);
实现类中实现该方法
获取索引位置和条目数
封装PageBean对象返回
public PageBean<Brand> selectByPage(int currentPage, int pageSize) {
//2. 获取SqlSession对象
SqlSession sqlSession = factory.openSession();
//3. 获取BrandMapper
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
//4. 计算开始索引
int begin = (currentPage - 1) * pageSize;
// 每页条目数
int size = pageSize;
//5. 获取当前页数据
List<Brand> rows = mapper.selectByPage(begin, size);
// 获取数据总数
int totalCount = mapper.selectTotalCount();
//6. 封装PageBean对象
PageBean<Brand> pageBean = new PageBean<>();
pageBean.setRows(rows);
pageBean.setTotalCount(totalCount);
//7. 释放资源
sqlSession.close();
return pageBean;
}
4. Web层
这里获取当前页码 和 每页展示条数,是通过get请求方式来获取参数信息
getParameter()
,接收表单的get请求的参数
public void selectByPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 接收 当前页码 和 每页展示条数 url?currentPage=1&pageSize=5
String _currentPage = request.getParameter("currentPage");
String _pageSize = request.getParameter("pageSize");
int currentPage = Integer.parseInt(_currentPage);
int pageSize = Integer.parseInt(_pageSize);
//2. 调用service查询
PageBean<Brand> pageBean = brandService.selectByPage(currentPage, pageSize);
//3. 转为JSON
String jsonString = JSON.toJSONString(pageBean);
//4. 写数据
response.setContentType("text/json;charset=utf-8");
response.getWriter().write(jsonString);
}
5. 前端
selectAll(){
var _this = this;
axios({
method:"post",
url:"http://localhost:8080/brand-project/brand/selectByPage?currentPage="+this.currentPage+"&pageSize="+this.pageSize,
}).then(function (resp) {
//设置表格数据
_this.tableData = resp.data.rows; // {rows:[],totalCount:100}
//设置总记录数
_this.totalCount = resp.data.totalCount;
})
},
//分页
handleSizeChange(val) {
//console.log(`每页 ${val} 条`);
// 重新设置每页显示的条数
this.pageSize = val;
this.selectAll();
},
handleCurrentChange(val) {
//console.log(`当前页: ${val}`);
// 重新设置当前页码
this.currentPage = val;
this.selectAll();
},