【问题标题】:How to access to field when iterating over 2d array in Thymeleaf?在 Thymeleaf 中迭代二维数组时如何访问字段?
【发布时间】:2020-08-20 08:02:36
【问题描述】:

目前我正在学习 Thymeleaf。我想向用户展示包含按钮和值的简单网格。问题是在迭代期间我无法访问 Java 对象的变量。二维数组由 SeatsSeances 对象组成。

@AllArgsConstructor
@NoArgsConstructor
@Builder
@Data
public class SeatsSeance {
    private Integer id;
    private Integer seatId;
    private Integer seanceId;
    private SeatState state;
}
<table>
<tr th:each="row: ${seatSeances}">
<td th:each="place: ${row}">

<input type="button" th:text="${place.state.name()}"> //not working
<input type="button" th:text="${place.getState().name()}"> //not working

</td>
</tr>
</table>

当我只是尝试th:text="${place.state.name()}" 时出现错误:

Thu Aug 20 09:38:54 CEST 2020
There was an unexpected error (type=Internal Server Error, status=500).
An error happened during template parsing (template: "class path resource [templates/buyticket.html]")
org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/buyticket.html]")

我做错了什么? &lt;td th:each&gt; 标签里面应该是什么?

更新 1

SeatSeance 类:

@AllArgsConstructor
@NoArgsConstructor
@Builder
@Data
public class SeatsSeance {
    private Integer id;
    private Integer seatId;
    private Integer seanceId;
    private SeatState state;
} 

座位状态类

public enum SeatState { RESERVED, ORDERED, FREE
}

IDE 允许我使用 HTML 中的所有字段,因此问题不在于可访问性。更重要的是,使用没有问题

&lt;input type="button" th:text="${place}"&gt;

当我想显示对象的一个​​字段时,问题就开始了。尽管有 getter 和 setter,但我不能这样做

更新 2

【问题讨论】:

  • 可以添加完整的错误日志吗?
  • 如果日志太长怎么办?在我看来,以下可能是最重要的 org.thymeleaf.exceptions.TemplateInputException: An error occurred during template parsing (template: "class path resource [templates/buyticket.html]") Caused by: org.springframework.expression .spel.SpelEvaluationException: EL1007E: 在 null 上找不到属性或字段 'id' 原因:org.springframework.expression.spel.SpelEvaluationException: EL1007E: 在 null 上找不到属性或字段 'id'
  • 你有它! “在 null 上找不到属性或字段 'id'”。这意味着 Thymeleaf 正在尝试呈现为空的对象的 id 属性。 HTML 是否完整?您是否尝试在某处处理 id 属性?
  • 你能添加你的 SeatState.java 类吗?
  • 还要检查您在 SeatState.java 中的 name() 方法是否具有公共访问修饰符

标签: java arrays spring spring-boot thymeleaf


【解决方案1】:

您必须为类的所有属性提供 getter/setter。如果使用 Spring Lombok,则需要添加@Getter @Setter 标签。

【讨论】:

  • 我有所有的 getter 和 setter。 SeatsSeances 类已经有注释@Data,其中包含:@Getter , @Setter , @ToString , @EqualsAndHashCode and @RequiredArgsConstructor 注释
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多