Spring MVC / Thymeleaf-空值不保留到模型中

时间:2019-03-04 18:52:22

标签: java spring-boot spring-mvc entity thymeleaf

我在Thymeleaf和Spring MVC上遇到了一些麻烦。我有一个由连接到SQL数据库的存储库管理的实体类。

在我的控制器中,我将返回的实体列表添加到模型中,并尝试在模板中访问它们。问题是,当该实体的字段之一为空时,当尝试访问该字段时,它将以以下格式返回SpEL错误。

Exception evaluating SpringEL expression: "entity.phoneNumber" (template: "index" - line 13, col 17)

就像我之前提到的,只有当Entity的字段之一为null时,才会发生这种情况。我尝试使用像这样的安全导航操作符...

entity?.phoneNumber

但这是空的属性,而不是实体本身。

我也尝试过使用类似的方法,但这也会返回一个错误,因为它甚至找不到该属性以查看其是否为空。

<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>

我反复检查了拼写错误。当我仅查看保证具有值的属性时,一切都会按预期进行。只有属性有可能为null的属性才会引起问题。

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

由于我弄清楚是什么原因造成的,因此提供了更新。实体类具有用于使用trim()函数从数据库中删除尾随空格的getter,因为它使用的是char而不是varchar。空值不能被修剪,因此我只需要更改吸气剂就可以解决空值。

return phoneNumber == null ? null : phoneNumber.trim();