Java 如何在一次操作中使用 Thymeleaf 检查空和空条件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51301074/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 00:03:34  来源:igfitidea点击:

How to check null and empty condition using Thymeleaf in one single operation?

javathymeleafisnullorempty

提问by Pradeep

Is there any way to check both null and empty condition in Thymeleaf?

有没有办法检查 Thymeleaf 中的空和空条件?

Approach 1

方法一

1) .variable1?.variable2?.variable3
2) variable!=null 
3) variable!=''

If we combine two conditions like (variable!='' And variable!=null) I am having issue when rendering.

如果我们结合两个条件,如 (variable!='' And variable!=null) 我在渲染时遇到问题。

I am trying following sample

我正在尝试以下示例

${#strings.concat(#strings.concat('class ',variable1?.variable2), ' ', variable1?.variable2?.variable3)}

I also used containsKeyas well but it is behaving differently.

我也使用了containsKey但它的行为有所不同。

采纳答案by Sumit

In order to check null or empty string using thymeleaf expressions, Use this approach : ---

为了使用 thymeleaf 表达式检查空字符串或空字符串,请使用以下方法:---

<div th:if= "${searchResults.results != null}">

OR, this :--

或这个 : -

<div th:if= "${searchResults.results != ''}">

Furthermore, you can check the empty or null object on your controller itself and then send the response on your thymeleaf-html page accordingly, like this :--
1.) Your Controller :-

此外,您可以检查控制器本身上的空或空对象,然后相应地在 thymeleaf-html 页面上发送响应,如下所示:--
1.) 您的控制器 :-

 List ls = //some data from you DAO
    if(ls.isEmpty()){
         model.addAttribute("response","NoData");
      }else{
         model.addAttribute("response",ls);
     }

2.) Then on your Thymleaf page :- - -

2.) 然后在您的 Thymleaf 页面上:- - -

<th:block th:if="${response=='NoData'}"> No Data Found </th:block>

PS -I've answered the same question here which helps the questioner hope it helps you as well :-- ThymeLeaf: Not Equal expression in th:if

PS -我在这里回答了同样的问题,这有助于提问者,希望它也能帮助你 :-- ThymeLeaf: Not Equal expression in th:if

回答by naXa

Try ${#strings.isEmpty(variable)}.

试试${#strings.isEmpty(variable)}

From Tutorial | Using Thymeleaf | Strings:

教程 | 使用百里香| 字符串

/*
 * Check whether a String is empty (or null). Performs a trim() operation before check
 */
${#strings.isEmpty(name)}