【发布时间】:2021-04-07 05:28:37
【问题描述】:
我尝试对我的用户 CRUD 进行分页,但它不起作用。我可以打开 users.html,它只显示 3 条记录,这很好,如果我手动使用 localhost:9001/users/page/1、2 等,它工作正常。但是表下的分页器是报错画面。
我的用户控制器:
@GetMapping("users/page/{pageNo}")
public String findPaginated(@PathVariable (value="pageNo") int pageNo, Model model) {
int pageSize = 3; //only 3 so I can easily test it
Page<User> page = userService.findPaginated(pageNo, pageSize);
List<User> listUsers = page.getContent();
model.addAttribute("currentPage", pageNo);
model.addAttribute("totalPages", page.getTotalPages());
model.addAttribute("totalItems", page.getTotalElements());
model.addAttribute("listUsers", listUsers);
return "/users";
}
**and**
@GetMapping("/users")
public String viewHomePage (Model model) {
//model.addAttribute("listUsers", userService.getAllUsers());
return findPaginated(1, model);
}
我的用户服务:
Page<User> findPaginated(int pageNo, int pageSize);
UserServiceImpl:
@Override
public Page<User> findPaginated(int PageNo, int PageSize) {
Pageable pageable = PageRequest.of(PageNo -1, PageSize);
return this.userRepository.findAll(pageable);
}
UserResository 扩展了 JpaRepository:
public interface UserRepository extends JpaRepository<User, Long> {
users.html 中的分页:
<div th:if="${totalPages > 1}">
<div class="row col-sm-10">
<div class="col-sm-2">
<!--Total Rows: [[{$totalItems}]]
</div>
<div class="col-sm-1">
<span th:each="i: ${#numbers.sequence(1, totalPages)}">
valami
<a th:if="${currentPage != i}" th:href="@{'/page/' + ${i}}">[[${i}]]</a>
<span th:unless="${currentPage != i">[[${i}]]</span>
</span>
</div>
<!-- <div class="col-sm-1">
<a th:if="${currentPage < totalPages}" th:href="@{'/page/' + ${currentPage + 1}}">Következő</a>
<span th:unless="${currentPage < totalPages}">Következő</span>
</div>
<div class="col-sm-1">
<a th:if="${currentPage < totalPages}" th:href="@{'/page/' + ${totalPages}}">Utolsó</a>
<span th:unless="${currentPage < totalPages}">Utolsó</span>
</div>
</div>
即使我把这部分html注释掉,还是会显示错误。
错误:
An error happened during template parsing (template: "class path resource [templates//users.html]")
Could not parse as expression: "{$totalItems}" (template: "/users" - line 132, col 24)
总结: 仅显示 3 条记录 - 有效 使用 url 之类的 /users/page/2 - 手动工作 在表格下显示数字和页面 - 不起作用
【问题讨论】:
标签: spring-boot pagination thymeleaf