1.整合 thymeleaf 需要 thymeleaf 驱动器
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.在application.properties 中配置 thymeleaf
#thymeleaf
spring.thymeleaf.cache=false
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html
spring.thymeleaf.prefix=classpath:/templates
spring.thymeleaf.suffix=.html
3.thymeleaf配置好,分页也需要启动器,导入分页启动器
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.0</version>
</dependency>
4.开始编写分页接口,以及实现类。分页的开始是从service层开始,所以前面两层省略!!!!
注意:mapper层必须托管,在类上面加上@mapper注解,不然下面无法获取
service接口
PageInfo<Emp> findAll(int pageNum, int pageSize);
service的impl的实现类
@Autowired
private EmpMapper empMapper;
@Override
public PageInfo<Emp> findAll(int pageNum, int pageSize) {
//1、设置 Pagehelper 分页的页数,每页的长度 需要拦截器
PageHelper.startPage(pageNum,pageSize);
//2、查询所有
List<Emp> accountList = empMapper.findAll();
//3、将分页结果封装
PageInfo<Emp> pageInfo = new PageInfo<>(accountList);
System.out.println(pageInfo);
//返回pageInfo类型的数据
return pageInfo;
}
controller层,使用视图转发解析
@Controller
public class EmpController {
@Autowired
private EmpService empService;
@GetMapping("/findAll")
public ModelAndView findAll(int pageNum, int pageSize) {
System.out.println(pageNum);
System.out.println(pageSize);
PageInfo<Emp> serviceAll = empService.findAll(pageNum, pageSize);
ModelAndView mv = new ModelAndView();
mv.addObject("emps",serviceAll);
mv.setViewName("/FenYe");
return mv;
}
}
5.resources下的templates下创建html文件
<body>
<h1>用户列表</h1>
<table class="table table-hover">
<tr>
<th>编号</th>
<th>姓名</th>
<th>性别</th>
<th>电话</th>
<th>用户姓名</th>
</tr>
<tr th:each="emp : ${emps.list}">
<td th:text="${emp.eId}">neo</td>
<td th:text="${emp.eName}">Otto</td>
<td th:text="${emp.eSex}">6</td>
<td th:text="${emp.eTel}">6</td>
<td th:text="${emp.username}">6</td>
</tr>
</table>
<div>
<a href="#" th:href="'/findAll?pageNum=1&pageSize=5'">首页</a>
<a href="#" th:href="'/findAll?pageNum='+${emps.prePage}+'&pageSize=5'">上一页</a>
<a href="#" th:href="'/findAll?pageNum='+${emps.nextPage}+'&pageSize=5'">下一页</a>
<a href="#" th:href="'/findAll?pageNum='+${emps.pages}+'&pageSize=5'">尾页</a>
<span th:text="'当前页:'+${emps.pageNum}"> </span>
<span th:text="'当前页条数:'+${emps.size}"> </span>
<span th:text="'总条数:'+${emps.total}"> </span>
<span th:text="'总页数:'+${emps.pages}"> </span>
</div>
</div>
</body>
最终效果