【问题标题】:Spring MVC / Thymeleaf - Null values not carrying over to modelSpring MVC / Thymeleaf - Null 值不会延续到模型
【发布时间】:2019-03-04 18:52:21
【问题描述】:

我在使用 Thymeleaf 和 Spring MVC 时遇到了一些问题。我有一个由连接到 SQL 数据库的存储库管理的实体类。

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

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

就像我之前提到的,这只发生在实体的字段之一为空时。我尝试使用这样的安全导航运算符...

entity?.phoneNumber

但它是 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>

我已反复检查是否有拼写错误。当我只查看保证具有值的属性时,一切都按预期工作。只有有可能为 null 的属性才会导致问题。

任何帮助将不胜感激!

【问题讨论】:

  • 这非常强烈地表明您的实体实际上是空的。尝试插入&lt;span th:text="${entity}" /&gt; 看看你会得到什么。
  • 您好@chrylis,感谢您的回复。当将其更改为 ${entities} 因为它是一个实体列表时,我最终会在页面上看到一个巨大的数组,其中包含(公司信息已删除)“com.****.mvctest.model.entity.* **.ActiveCustomersEntity@d17ec6f”。但是,我知道模型本身不为空,因为正如我之前提到的,我可以访问所有保证具有非空值的字段。此外,我尝试一次获取一个实体,所有字段都存在的实体没有问题,而具有空字段的实体则抛出 SpEL 错误。
  • 如果${entity} 不为空,那么表达式${entity.phoneNumber} 永远不会抛出错误(在普通的getter 和setter 用例中)——它只会输出一个空字符串。根据您共享的代码,这里还有其他事情发生,我们没有足够的信息来提供帮助。
  • 我正在使用 Lombok 项目来自动创建我的 getter 和 setter。我想知道这是否与这个问题有关。在将实体传递给模型之前,我还将尝试将实体映射到 DTO,看看是否有帮助。明天我将尝试更多的事情,并将更新此线程。感谢您到目前为止的回答!
  • 请查看此链接stackoverflow.com/questions/49845057/… 我相信如果您确实在没有 Lombok 的情况下生成了 getter/setter 方法,那么根据您当前发布的代码,一切都应该没问题。

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


【解决方案1】:

提供更新,因为我找出了造成这种情况的原因。实体类具有使用 trim() 函数从数据库中删除尾随空格的 getter,因为它使用的是 char 而不是 varchar。无法修剪空值,因此我只需要更改我的 getter 以考虑空值。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-27
    • 2020-03-14
    • 1970-01-01
    • 1970-01-01
    • 2016-06-18
    • 2014-08-22
    • 2018-01-07
    • 2018-06-12
    相关资源
    最近更新 更多