Spring MVC / Thymeleaf - 空值未转移到模型
Spring MVC / Thymeleaf - Null values not carrying over to model
我在使用 Thymeleaf 和 Spring MVC 时遇到了一些问题。我有一个实体 class,由连接到 SQL 数据库的存储库管理。
在我的控制器中,我将返回的实体列表添加到我的模型中,并尝试在我的模板中访问这些实体。问题是,当该实体的一个字段为空时,当尝试访问该字段时,它 returns 出现以下格式的 SpEL 错误。
Exception evaluating SpringEL expression: "entity.phoneNumber" (template: "index" - line 13, col 17)
就像我之前提到的,只有当实体的一个字段为空时才会发生这种情况。我试过像这样使用安全导航运算符...
entity?.phoneNumber
但它是 null 的属性,而不是实体本身。
我也尝试过使用类似的东西,但这也是 returns 一个错误,因为它甚至找不到属性来查看它是否为 null。
<span th:if="${entity.phoneNumber != null}" th:text="${entity.phoneNumber}">Phone Number</span>
控制器看起来像这样。
@Controller
public class IndexController {
@Autowired
CustomerService customerService;
@GetMapping
public String index(Model model) {
List<ActiveCustomersEntity> entities = customerService.getAllCustomers();
model.addAttribute("entities", entities);
return "index";
}
}
现在我的模板是这样的。
<!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>
我反复检查了拼写错误。当我只查看保证有值的属性时,一切都按预期工作。只有属性有可能为空才会导致问题。
如有任何帮助,我们将不胜感激!
提供更新,因为我弄清楚了是什么原因造成的。实体 class 具有使用 trim() 函数从数据库中删除尾随空格的 getter,因为它使用的是 char 而不是 varchar。 Null 值不能 trimmed,所以我只需要更改我的 getters 来解释 null 值。
return phoneNumber == null ? null : phoneNumber.trim();
我在使用 Thymeleaf 和 Spring MVC 时遇到了一些问题。我有一个实体 class,由连接到 SQL 数据库的存储库管理。
在我的控制器中,我将返回的实体列表添加到我的模型中,并尝试在我的模板中访问这些实体。问题是,当该实体的一个字段为空时,当尝试访问该字段时,它 returns 出现以下格式的 SpEL 错误。
Exception evaluating SpringEL expression: "entity.phoneNumber" (template: "index" - line 13, col 17)
就像我之前提到的,只有当实体的一个字段为空时才会发生这种情况。我试过像这样使用安全导航运算符...
entity?.phoneNumber
但它是 null 的属性,而不是实体本身。
我也尝试过使用类似的东西,但这也是 returns 一个错误,因为它甚至找不到属性来查看它是否为 null。
<span th:if="${entity.phoneNumber != null}" th:text="${entity.phoneNumber}">Phone Number</span>
控制器看起来像这样。
@Controller
public class IndexController {
@Autowired
CustomerService customerService;
@GetMapping
public String index(Model model) {
List<ActiveCustomersEntity> entities = customerService.getAllCustomers();
model.addAttribute("entities", entities);
return "index";
}
}
现在我的模板是这样的。
<!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>
我反复检查了拼写错误。当我只查看保证有值的属性时,一切都按预期工作。只有属性有可能为空才会导致问题。
如有任何帮助,我们将不胜感激!
提供更新,因为我弄清楚了是什么原因造成的。实体 class 具有使用 trim() 函数从数据库中删除尾随空格的 getter,因为它使用的是 char 而不是 varchar。 Null 值不能 trimmed,所以我只需要更改我的 getters 来解释 null 值。
return phoneNumber == null ? null : phoneNumber.trim();