Thymeleaf实现数据分页

发布于:2024-03-29 ⋅ 阅读:(15) ⋅ 点赞:(0)

1、介绍

在Thymeleaf中实现数据分页通常需要后端服务的支持,因为分页逻辑通常在服务器端进行。后端服务将分页后的数据传递给Thymeleaf模板进行渲染。使用到组件有Thymeleaf+MybatisPlus+PageHelper。

2、分页实现

服务端Controller代码

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @GetMapping("/list")
    public String list(Model model,Integer pageNum){
        PageHelper.startPage(pageNum,3);
        List<User> users = userService.list();
        PageInfo<User> userPageInfo = new PageInfo<>(users);
        model.addAttribute("userPageInfo", userPageInfo);
        return "user/list";
    }

    @GetMapping("/detail")
    public String detail(Long id){
        return "user/detail";
    }

}

Thymeleaf模板

<!DOCTYPE html>  
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>  
    <meta charset="UTF-8">  
    <meta name="viewport" content="width=device-width, initial-scale=1.0">  
    <title>简历列表</title>
    <!--style 省略-->
</head>  
<body>  
    <h1>简历列表</h1>
    <ul class="resume-list" th:with="users=${userPageInfo.list}">
        <li class="resume-item" th:each="user:${users}">
            <a href="/user/detail">
                <h2 th:text="${user.name}">张三</h2>
                <p th:text="${user.introduce}">软件工程师,具有5年工作经验,擅长Java和前端技术。</p>
                <p th:text="${user.phone}">联系方式:123-4567-8901</p>
            </a>
        </li>
    </ul>
<div class="page-foot">
    <a th:class="${pageNum==userPageInfo.pageNum?'active':''}" 
    th:href="'/user/list?pageNum='+${pageNum}" 
    th:each="pageNum:${userPageInfo.navigatepageNums}" >[[${pageNum}]]</a>
</div>
</body>
</html>

渲染结果
在这里插入图片描述

本文含有隐藏内容,请 开通VIP 后查看