Thymeleaf异常-TemplateProcessingException Exception evaluating SpringEL expression - Property or field 'x' cannot be found on object of type 'java.util.HashMap'

目录
  1. 问题
  2. 解决

问题

1
2
3
<div th:each="item:${list}">
<div th:text="${item.show}"></div>
</div>

thymeleaf 循环list时,若item里存在空值,即show为空时,可能会出现如下错误。

1
2
3
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "item.show" (template: "index" - line 37, col 82)
...
Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'show' cannot be found on object of type 'java.util.HashMap' - maybe not public or not valid?

解决

使用map的方式获取值,即使用 ${item.get(‘show’)} 替换 ${item.show}。

1
2
3
<div th:each="item:${list}">
<div th:text="${item.get('show')}"></div>
</div>

成功渲染。

Thymeleaf相关链接:

Thymeleaf List指定数量循环
Thymeleaf SAXParseException
Thymeleaf实现页面静态化
Thymeleaf比较判断枚举类型