【spring boot】【thymeleaf】SPEL处理 null 值
前言
- spring boot 2.1.1.RELEASE
- thymeleaf 3.0
變量為 null 時,顯示默認(rèn)值
name?:'Unknown'
當(dāng) name 變量為 null 時,顯示值 Unknown。等價于 name?name:'Unknown'。
對象為 null 時,避免調(diào)用方法或?qū)傩猿鲥e
placeOfBirth?.city
當(dāng) placeOfBirth 為 null 時,不再繼續(xù)調(diào)用屬性 city。
code?.toUpperCase()
當(dāng) code 為 null 時,不再繼續(xù)調(diào)用方法 toUpperCase。
Map 獲取的元素為 null
當(dāng) map 中沒有名為 name 的元素時,這樣寫會報錯 map.name。
安全的寫法是這樣:map['name']。
如果 map 中的元素為對象時,可以這樣寫:map['user']?.name。
List 類型數(shù)組越界
數(shù)組越界時,錯誤是這樣的:
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 invalidSPEL 是這樣的 slist[2].score,但 slist 不夠3個元素(EL1025E: The collection has '1' elements, index '2' is invalid),因此數(shù)組越界了。
解決辦法:添加數(shù)組大小的判斷。上面的情況下,用 #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
總結(jié)
以上是生活随笔為你收集整理的【spring boot】【thymeleaf】SPEL处理 null 值的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 百级分区背光:小米 86 寸 ES Pr
- 下一篇: 夸克健康助手入选2023世界互联网大会《