【Java】EL1008E: Property or field 'xxx' cannot be found on object of type

springboot 集成thymeleaf渲染页面

项目中使用到了thymeleaf作为模板渲染页面,模板数据中有部分属性根据不同条件会有不存在的情况,当页面中使用了该字段,并且字段不存在的时候,则会报错,特别是在多级结构的情况下

报错如下:
EL1008E: Property or field 'xxx' cannot be found on object of type xxx...
错误代码如下:
<span th:text="${#numbers.formatInteger(scale.ext.price, 0)}"></span>

当price属性不存在时:EL1008E: Property or field 'price' cannot be found on object of type

网上搜索了n多文章,大多介绍三目运算符的方式,尝试之后发现还会报错;
最后终于找到了可用方案,做一下备忘:

解决办法:

//使用map的方式获取值,即使用 ${scale.ext.get('price')} 替换 ${scale.ext.price}。

<span th:text="${#numbers.formatInteger(scale.ext.get('price'), 0)}"></span>

优化处理:

//当scale.ext为空的情况

<span th:text="${#numbers.formatInteger(scale?.ext?.get('price'), 0)}"></span>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容