spring-boot - 如何打印出在 Thymeleaf 中按字母分组的列表中的元素?
问题描述
我有以下数据库表:
CREATE TABLE authors
(
id INT AUTO_INCREMENT PRIMARY KEY,
authorName VARCHAR(250) NOT NULL
);
我想按如下方式打印我们的作者:
一个
- 安塞尔玛麦肯南
乙
- 伯蒂·甘德利
- 贝蒂安·阿斯肯
C
- 牧师德贾科维奇
- 克里斯蒂·艾萨克森
D
- 丹尼滑翔机
- 达西·侯麦
- 多姆·罗布雄
目前我通过thymleaf模板打印如下,不想每次都在作者面前打印出Alphabet LETTER:
一个
- 安塞尔玛麦肯南
乙
- 伯蒂·甘德利
乙
- 贝蒂安·阿斯肯
C
- 牧师德贾科维奇
C
- 克里斯蒂·艾萨克森
D
- 丹尼滑翔机
D
- 达西·侯麦
D
- 多姆·罗布雄
我的控制器:
@GetMapping("/index.html")
public String mainPage(Model model) {
model.addAttribute("authorsData", bookService.getAuthorData());
return "/authors/index";
}
我的服务:
public List<Author> getAuthorData() {
List<Author> authors = jdbcTemplate.query("SELECT id, authorName from authors ORDER BY authorName", (ResultSet rs, int rowNum) -> {
Author author = new Author();
author.setId(rs.getInt("id"));
author.setAuthorName(rs.getString("authorName"));
return author;
});
return new ArrayList<>(authors);
}
我的百里香代码如下:
<div class="Authors-block" th:each="author : ${authorsData}" >
<h2 class="Authors-title" id="a" th:text="${author.getAuthorName().charAt(0)}">
</h2>
<div class="Authors-letter">
<div class="Authors-item"><a href="/authors/slug.html" th:text="${author.getAuthorName()}"></a>
</div>
解决方案
让您的 getAuthorData() 返回 Map<Character, List> 其中键是字母,值是作者以该字母开头
public List<Author> getAuthorData() {
List<Author> authors = jdbcTemplate.query("SELECT id, authorName from authors ORDER BY
authorName", (ResultSet rs, int rowNum) -> {
Author author = new Author();
author.setId(rs.getInt("id"));
author.setAuthorName(rs.getString("authorName"));
return author;
});
return authors.stream()
.collect(
Collectors.groupingBy(
author -> author.getAuthorName().charAt(0)
)
);
}
在 html 中,您可以遍历地图条目,如下所示:How to loop through Map in Thymeleaf 只需注意作为一个值,您将拥有可迭代数组
推荐阅读
- r - 如何使用 dplyr group_by 并获取每个不同分组的索引?
- python-3.x - 如何在 py3 代码中将列表转换为 scapy.plist.PacketList?
- recursion - 不能接受 2 的 CAR(Common Lisp)
- mysql - 错误:1452 - 添加触发器后插入操作失败
- nginx - Kong 2.0.2 服务 api 和静态内容
- javascript - 如何切换触发器
- windows - PowerShell Core 在线设置打印机
- linux - 链接时ssl版本冲突
- python - 熊猫分配和复制
- python - 不可散列的类型:'list' - 出了什么问题?