1)pom.xml
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.10</version>
</dependency>
2)application.yml
spring:
datasource:
url: jdbc:mysql://localhost:3306/javaee
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: "00000000" #密码加双引号
mybatis:
configuration:
map-underscore-to-camel-case: true #开启驼峰命名映射
#分页配置
pagehelper:
helper-dialect: mysql
reasonable: true
support-methods-arguments: true
params: count=countSql
3)controller
@Controller
public class IndexController {
@Autowired
ArticleService articleService;
@GetMapping("/")
public String getArticleList(Model model,
HttpServletRequest request,
@RequestParam(value = "pageNum",
defaultValue = "1",
required = false) int pageNum,
@RequestParam(value = "pageSize",
defaultValue = "6") int pageSize){
//pageNum前端传来的页号,pageSize每页的条数
Page page = PageHelper.startPage(pageNum,pageSize);
List<ArticleDTO> articleDTOS = articleService.getArticleDTOS();
PageInfo<ArticleDTO> pageInfo = new PageInfo<>(page.getResult());
model.addAttribute("articles",articleDTOS); //获取文章传输对象放到前端
model.addAttribute("pageInfo",pageInfo);
return "index";
}
}
4)前端Thymeleaf
<nav aria-label="Page navigation" style="float: right">
<ul class="pagination">
<!--首页-->
<li >
<a th:href="'/?pageNum='+${pageInfo.navigateFirstPage}" >首页</a>
</li>
<!--上一页-->
<li th:if="${pageInfo.hasPreviousPage}">
<a th:href="'/?pageNum=' + ${pageInfo.prePage}" aria-label="Previous">
<span aria-hidden="true">上一页</span>
</a>
</li>
<!--遍历当前显示的页号,假如当前页为6 遍历后只显示4 5 6 7 8-->
<th:block th:each="nav : ${pageInfo.navigatepageNums}" >
<li th:class="${nav==pageInfo.pageNum}?'active':'' "
th:if="${(nav < (pageInfo.pageNum-2))||(nav > (pageInfo.pageNum+2)) ?'false':'true'}" >
<a th:href="'/?pageNum=' + ${nav}"
th:text="${nav}">
</a>
</li>
</th:block>
<!--下一页-->
<li th:if="${pageInfo.hasNextPage}">
<a th:href="'/?pageNum=' + ${pageInfo.nextPage}" aria-label="Next">
<span aria-hidden="true">下一页</span>
</a>
</li>
<!--尾页-->
<li>
<a th:href="'/?pageNum='+${pageInfo.navigateLastPage}">尾页</a>
</li>
</ul>
</nav>