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

Pra*_*eep 5 java isnullorempty thymeleaf

有什么方法可以同时检查Thymeleaf中的空值和空值吗?

方法1

1) .variable1?.variable2?.variable3
2) variable!=null 
3) variable!=''
Run Code Online (Sandbox Code Playgroud)

如果我们组合两个条件,例如(variable!=''和variable!= null),则渲染时出现问题。

我正在尝试追踪样本

${#strings.concat(#strings.concat('class ',variable1?.variable2), ' ', variable1?.variable2?.variable3)}
Run Code Online (Sandbox Code Playgroud)

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

naX*_*aXa 16

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

教程| 使用Thymeleaf | 字串

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

  • @FarazDurrani 这取决于你需要什么。如果 `name` 为 null 或为空,则 `${#strings.isEmpty(name)}` 为真。`${!#strings.isEmpty(name)}` 或 `${not #strings.isEmpty(name)}` 为真,如果 `name` 不为 null 且不为空。 (3认同)

Sum*_*mit 5

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

<div th:if= "${searchResults.results != null}">
Run Code Online (Sandbox Code Playgroud)

或这个 : -

<div th:if= "${searchResults.results != ''}">
Run Code Online (Sandbox Code Playgroud)

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

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

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

<th:block th:if="${response=='NoData'}"> No Data Found </th:block>
Run Code Online (Sandbox Code Playgroud)

PS-我在这里回答了同样的问题,这有助于发问者希望它也对您有帮助:- 百里香叶:th:if中的表达不均等