Springboot Thymeleaf 检查String是否为 null 或空白字符串

Java 2020-02-20 阅读 1496 评论 0

使用 springboot 项目的 thymeleaf 前端模版,判断一个字符串是否为空(String 为 null、空字符或者只包含空白符)的几种方法。

使用 String 的 trim() 方法

<div th:if="${str != null && str.trim() != ''}" th:text="${str}"/>

使用 Strings 的 isEmpty() 方法

Thymeleaf 的 Strings 类,包含类多个常用的判断,可以参考 Strings 的 api org.thymeleaf.expression.Strings,还有一些字符串拼接、集合 List,Set 的操作等,非常有用的一个工具类。

isEmpty() 的源代码如下。空对象,或者只包含了空白字符的,表明就是空的,返回 true。

public Boolean isEmpty(final Object target) {
    return Boolean.valueOf(target == null || StringUtils.isEmptyOrWhitespace(target.toString()));
}

以下3种写法都是一样的效果,使用类th:ifth:unless条件判断。

<div th:if="!${#strings.isEmpty(str)}" th:text="${str}"/>
<div th:if="${!#strings.isEmpty(str)}" th:text="${str}"/>
<div th:unless="${#strings.isEmpty(str)}" th:text="${str}"/>

使用 isEmpty() 方法

这一方法与上一步的方法一致。

<div th:unless="${str.isEmpty()}" th:text="${str}"/>
最后更新 2020-02-20