You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Thymeleaf的#temporals.format()时抛出NullPointerException求助

Thymeleaf格式化LocalDate时抛出NullPointerException问题

我尝试在Thymeleaf中按如下方式格式化LocalDate:

<div th:object="${objectWithDateField}">
    <span th:text="*{#temporals.format(date)}"></span>
</div>

但这会抛出NullPointerException,提示信息为:target is null for method format,其中target指的是format()方法的参数。

我的疑问是:这是我的操作错误,还是Thymeleaf的bug?

当不格式化日期,仅直接渲染时,日期能正常显示:

<div th:object="${objectWithDateField}">
    <span th:text="*{date}"></span>
</div>

目前我在单元测试中运行这段代码,已通过断言确认将对象传入上下文前date字段绝对不为null(直接渲染的结果也能验证这一点)。

我曾尝试过相关解决方案,但评论区有人遇到相同问题却未得到解答。

我使用的版本如下:

  • Spring Boot Starter Thymeleaf: 2.7.2
  • ognl: 3.2.1(未使用SpEL)

补充说明:我已注册了自定义的TemplateEngine Bean并添加@Primary注解,以便使用Thymeleaf的默认方言,代码如下:

@Bean
@Primary
public TemplateEngine myTemplateEngine() {
    ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
    templateResolver.setSuffix(".html");
    templateResolver.setTemplateMode(TemplateMode.HTML);

    TemplateEngine templateEngine = new TemplateEngine();
    templateEngine.setTemplateResolver(templateResolver);
    return templateEngine;
}

thymeleaf-extras-java8time已通过spring-boot-starter-thymeleaf间接引入,存在于运行时类路径中。

内容的提问来源于stack exchange,提问作者Malte Esch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 13:45:48