java - Spring Boot/Thymeleaf - 循环中的循环

标签 java spring-boot thymeleaf

我有一个应用程序,其中两个实体具有双向一对多关系。车主和自行车。

因此通过curl获取所有者将给出

[
    {"id":1,
    "userName":"user1",
    "bicycles":
        [
            {
                "id":1,
                "make":"dawes",
                "model":"civic",
                "owner":1
            }
        ]
    },
    {"id":2,
    "userName":"user2",
    "bicycles":
        [
            {
                "id":2,
                "make":"whyte",
                "model":"montpellier",
                "owner":2
            }
            ,{
                "id":4,
                "make":"dahon",
                "model":"tern A7",
                "owner":2
            }
        ]
    } ]

这很好。

如果我创建一个在表中循环的模板,

<table>
    <tr th:each="owner : ${owners}">
      <td th:text="${owner.userName}"></td>
      <td th:text="${owner.bicycles[0].make}"
          th:if="${#lists.size(owner.bicycles)} > 0">"</td>
      <td th:text="${owner.bicycles[0].model}"
          th:if="${#lists.size(owner.bicycles)} > 0"></td> 
    </tr>
  </table>

然后我在浏览器中得到了预期的结果。我意识到上面的代码很糟糕,但我现在只是想让 thymeleaf 工作起来。

但是如果我执行以下代码

<table>
    <tr th:each="owner : ${owners}">
      <td th:text="${owner.userName}"></td>
      <tr th:each="bike : ${owner.bicycles}">
          <td th:text="${bike.make}"></td>
          <td th:text="${bike.model}"></td>  
      </tr>  
    </tr>
  </table>

然后我收到以下控制台错误

nested exception is org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "owner.bicycles" (template: "nutsthymeleaf" - line 23, col 15)] with root cause

org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'bicycles' cannot be found on null

令我困惑的是,owner.bicycle[index] 可以工作。它显示品牌和型号。然而,根据错误,owner.bicycles 似乎是一个空字段。

很明显我做错了什么......

最佳答案

所以我找到了这个

Thymeleaf: Getting Property or field cannot be found on null. Iteration of list inside a list

这样就停止了 SpelException。

经过尝试,它不需要 3 个级别,而只需要两个。如果 th:each 嵌套在 th:each 中,就会出现问题。第二个 th:each 必须位于 th:block(或可能是 div)中。

关于java - Spring Boot/Thymeleaf - 循环中的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56737634/

相关文章:

java - 表情符号在 ajax 后在 MySQL 表列和 HTML 中呈现,但在页面重新加载后不会呈现。为什么?

java - if(pause == null) { 不起作用

java - OneToManyToMany 连续三个带有 Hibernate Annotations 的表

java - 在现有应用程序中实现缓存

unit-testing - 使用包含 Autowiring 属性的 ControllerAdvice 进行 WebMvc 测试

html - th :href and href when linking absolute URLs in Thymeleaf之间的区别

java - 即时生成 PDF 文件

Eclipse 的 Java 存储库与 Maven : Missing artifact:compile

java - 项目构建错误: Non-resolvable parent POM cannot find repository

java - 组织.hibernate.HibernateException : Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set