【发布时间】:2020-08-03 02:00:31
【问题描述】:
<th:block th:each="item : ${mclist}" >
<option th:if="${item.id}" th:value="${item.id}" th:text="${item}"></option>
<option th:if="${item.id == null}" th:value="${item}" th:text="${item}"></option>
</th:block>
对象“item”可以是任何实体。因此,它可能包含也可能不包含“id”字段。当实体不包含“id”字段时,此处显示的代码会出现以下错误。
org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'id' cannot be found on object of type 'java.lang.String' - maybe not public or not valid?
是否可以在提取值之前检查 'item' 对象中是否存在 id 字段?
【问题讨论】:
-
我认为 Thymeleaf 中没有任何原生支持来检查对象上是否存在字段。您将要做的最好的事情是编写自己的辅助方法,如果对象具有 id 字段,则使用反射返回
true或false,并在 Thymeleaf 中使用它。虽然这是一些非常奇怪的设计......
标签: java spring spring-mvc jsp thymeleaf