如何在Thymeleaf中显示每个循环的对象集合?

Jus*_*Fun 4 java spring-mvc thymeleaf

我想用Spring MVC在浏览器中显示数据库中的数据.一切都没问题,除了每个循环的Thymeleaf模板.那里出了点问题.

如何idID行中显示数据,nameName行中显示数据,迭代每个循环的对象集合?

源代码:

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
     <title>Getting Started: Serving Web Content</title>
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <table border="1">
        <tr style="font-size: 13">
            <td>ID</td>
            <td>Name</td>
        </tr>
        <tr th:each="count :  ${id}">
            <td><p th:text="${count}" /></td>       
            <td><p th:text="${name}" /></td>        

        </tr>
    </table>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

Dim*_*San 13

你的问题不是很明确,因为你没有指定你的count对象,也没有显示你的控制器.

那么假设你有一些实体Count与字段idname,您可以在你的数据库的相应表坚持下去,并且要在Thymeleaf模板来显示.

要从数据库中检索数据,您需要一些ServiceRepository类,它应该具有返回List您的实体的方法,例如此类服务方法listAll():

public List<Count> listAll() {
    List<Count> counts = new ArrayList<>();
    countRepository.findAll().forEach(counts::add);
    return counts;
}
Run Code Online (Sandbox Code Playgroud)

然后,您需要在控制器中设置请求映射,并在该方法中添加属性到model对象,这将是执行listAll()方法的结果.可以这样做:

@RequestMapping("/list")
public String countsList(Model model) {
    model.addAttribute("counts", countService.listAll());
    return "list";
}
Run Code Online (Sandbox Code Playgroud)

最后回答你的问题,你的list.html模板应该包含块:

<div th:if="${not #lists.isEmpty(counts)}">
    <h2>Counts List</h2>
    <table class="table table-striped">
        <tr>
            <th>Id</th>
            <th>Name</th>
        </tr>
        <tr th:each="count : ${counts}">
            <td th:text="${count.id}"></td>
            <td th:text="${count.name}"></td>
        </tr>
    </table>
</div>
Run Code Online (Sandbox Code Playgroud)

阅读Thymeleaf文档 - 迭代基础知识部分中的更多信息.