Thymeleaf - 格式化时检查 NULL 的最佳实践(即日期) [英] Thymeleaf - Best practice for checking for NULL when formatting (ie. dates)

查看:25
本文介绍了Thymeleaf - 格式化时检查 NULL 的最佳实践(即日期)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Thymeleaf 模板代码来格式化日期.有时该日期在返回的对象中将为 null.在这种情况下,检查 Thymeleaf 中 null 的最佳方法是什么?当前模板抛出以下错误:

I have a Thymeleaf template code to format a date. There are times when that date will be null in the returned object. What is the best way to check for null in Thymeleaf in this situation? Currently the template is throwing the following error:

Caused by: java.lang.IllegalArgumentException: Cannot apply format on null
    at org.thymeleaf.util.Validate.notNull(Validate.java:37)
    at org.thymeleaf.util.DateUtils.format(DateUtils.java:182)
    at org.thymeleaf.expression.Dates.format(Dates.java:164)

推荐答案

你可以使用 thymeleafs 对象工具类 对象 或在将对象传递给模板之前对其进行验证.

you can either use thymeleafs objects utility class Objects or validate the object before passing it to the template.

我更喜欢预验证,因为您通常不想在模板中进行修改.也可以通过这种方式使数据与视图松散耦合.

i prefer the prevalidation as you normally do not want to hack around in your template. also that way you keep your data loosely coupled from the view.

这篇关于Thymeleaf - 格式化时检查 NULL 的最佳实践(即日期)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆