環(huán)境:springboot+mybatis+maven+yaml配置+前端用thymleaf模板(其實(shí)環(huán)境不太一樣也可以,我覺得我這種方法很簡單)
1.pom.xml添加依賴
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.13</version>
</dependency>
2.配置application.yaml
#配置分頁
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql
3.controller寫分頁代碼
- currentPage是當(dāng)前頁,pageSize是當(dāng)前頁的限制大小
- List<Type> list = typeService.listPage();是從數(shù)據(jù)庫中獲取所有的數(shù)據(jù)行,這個(gè)時(shí)候還沒有分頁。
- 然后如果list!=null。這個(gè)時(shí)候就把list放到PageInfo類型的變量中,然后才從PageInfo中獲得list,就完成了分頁。
- 把list返回前端。
@RequestMapping("/type")
public ModelAndView getTypes(@RequestParam(defaultValue = "1") Integer currentPage,
@RequestParam(defaultValue = "1") Integer pageSize){
ModelAndView model = new ModelAndView();
//1.開啟分頁
PageHelper.startPage(currentPage,pageSize);
List<Type> list = typeService.listPage();
//封裝list到PageInfo對(duì)象中,自動(dòng)分頁
PageInfo<Type> typePageInfo = null;
if(list!=null){
typePageInfo = new PageInfo<>(list);
list = typePageInfo.getList();
}
model.addObject("list",list);
model.setViewName("admin/types");
return model;
}
4.前端
<table >
<thead>
<tr><th>名稱</th>
<th>操作</th>
</tr></thead>
<tbody>
<tr th:each="temp: ${list}">
<td th:text="${temp.name}"></td>
<td>
<a href="#" class="ui mini teal basic button">編輯</a>
<a href="#" class="ui mini red basic button">刪除</a>
</td>
</tr>
</tbody>
</table>
5.結(jié)果
