我在使用 Thymeleaf 和 Spring MVC 時(shí)遇到了一些問題。我有一個(gè)由連接到 SQL 數(shù)據(jù)庫(kù)的存儲(chǔ)庫(kù)管理的實(shí)體類。在我的控制器中,我將返回的實(shí)體列表添加到我的模型中,并嘗試在我的模板中訪問這些實(shí)體。問題是,當(dāng)該實(shí)體的某個(gè)字段為空時(shí),當(dāng)嘗試訪問該字段時(shí),它會(huì)返回以下格式的 SpEL 錯(cuò)誤。Exception evaluating SpringEL expression: "entity.phoneNumber" (template: "index" - line 13, col 17)就像我之前提到的,這只發(fā)生在實(shí)體的一個(gè)字段為空時(shí)。我嘗試使用這樣的安全導(dǎo)航運(yùn)算符...entity?.phoneNumber但它是 null 的屬性,而不是實(shí)體本身。我也嘗試過使用類似的東西,但這也會(huì)返回錯(cuò)誤,因?yàn)樗踔翢o法找到屬性來查看它是否為空。<span th:if="${entity.phoneNumber != null}" th:text="${entity.phoneNumber}">Phone Number</span>控制器看起來像這樣。@Controllerpublic class IndexController {@AutowiredCustomerService customerService;@GetMappingpublic String index(Model model) { List<ActiveCustomersEntity> entities = customerService.getAllCustomers(); model.addAttribute("entities", entities); return "index"; }}現(xiàn)在我的模板看起來像這樣。<!DOCTYPE html><html xmlns:th="http://www.thymeleaf.org"><head> <meta charset="UTF-8"> <title>title</title></head><body> <table> <tr th:each="entity : ${entities}"> <td th:text="${entity.customerFormattedNm}">Customer Name</td> <td th:text="${entity.accountStatusCd}">Account Status Code</td> </tr> </table></body></html>我反復(fù)檢查拼寫錯(cuò)誤。當(dāng)我只查看保證具有值的屬性時(shí),一切都按預(yù)期工作。只有有機(jī)會(huì)為空的屬性才會(huì)導(dǎo)致問題。任何幫助,將不勝感激!
1 回答

DIEA
TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超3個(gè)贊
提供更新,因?yàn)槲艺页隽嗽斐蛇@種情況的原因。實(shí)體類具有使用 trim() 函數(shù)從數(shù)據(jù)庫(kù)中刪除尾隨空格的 getter,因?yàn)樗褂玫氖?char 而不是 varchar。無法修剪空值,因此我只需要更改我的 getter 即可考慮空值。
return phoneNumber == null ? null : phoneNumber.trim();
添加回答
舉報(bào)
0/150
提交
取消