【spring boot】【thymeleaf】SPEL处理 null 值
List 类型数组越界数组越界时,错误是这样的:Caused by: org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "slist[2].score" (template: "exam/papers/edit" - line 117, col 92)Cau
前言
- spring boot 2.1.1.RELEASE
- thymeleaf 3.0
变量为 null 时,显示默认值
name?:'Unknown'
当 name 变量为 null 时,显示值 Unknown。等价于 name?name:'Unknown'。
对象为 null 时,避免调用方法或属性出错
placeOfBirth?.city
当 placeOfBirth 为 null 时,不再继续调用属性 city。
code?.toUpperCase()
当 code 为 null 时,不再继续调用方法 toUpperCase。
Map 获取的元素为 null
当 map 中没有名为 name 的元素时,这样写会报错 map.name。
安全的写法是这样:map['name']。
如果 map 中的元素为对象时,可以这样写:map['user']?.name。
List 类型数组越界
数组越界时,错误是这样的:
Caused by: org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "slist[2].score" (template: "exam/papers/edit" - line 117, col 92)
Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1025E: The collection has '1' elements, index '2' is invalid
SPEL 是这样的 slist[2].score,但 slist 不够3个元素(EL1025E: The collection has '1' elements, index '2' is invalid),因此数组越界了。
解决办法:添加数组大小的判断。上面的情况下,用 #lists.size(slist)>=3?slist[2]?.score:0 替换 slist[2].score
参考
https://blog.csdn.net/sayyy/article/details/108011723
https://blog.csdn.net/sayyy/article/details/108011653
更多推荐
所有评论(0)