有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java:检查是否定义了变量

如何检查变量是否定义在Thymeleaf

Javascript中的类似内容:

if (typeof variable !== 'undefined') { }

或者在PHP中:

if (isset($var)) { }

百里香有没有等效的


共 (4) 个答案

  1. # 1 楼答案

    是的,您可以使用以下代码轻松检查文档是否存在给定属性。请注意,如果满足以下条件,您将创建div标记:

    <div th:if="${variable != null}" th:text="Yes, variable exists!">
       I wonder, if variable exists...
    </div>
    

    如果您想使用variable的字段,那么需要检查该字段是否也存在

    <div th:if="${variable != null && variable.name != null}" th:text="${variable.name}">
       I wonder, if variable.name exists...
    </div>
    

    甚至更短,不使用if语句

    <div th:text="${variable?.name}">
       I wonder, if variable.name exists...
    </div>`
    

    但是使用这个语句,不管variablevariable.name是否存在,您都将结束创建div标记

    您可以在thymeleafhere中了解有关条件的更多信息

  2. # 2 楼答案

    简表:

    <div th:if="${currentUser}">
        <h3>Name:</h3><h3 th:text="${currentUser.id}"></h3>
        <h3>Name:</h3><h3 th:text="${currentUser.username}"></h3>
    </div>
    
  3. # 3 楼答案

    为了判断上下文是否包含给定变量,可以直接询问上下文变量映射。这使我们可以确定是否指定了变量,而不是仅在定义了变量但其值为null的情况下

    胸腺素2

    使用^{}对象的^{}方法:

    <div th:if="${#vars.containsKey('myVariable')}" th:text="Yes, $myVariable exists!"></div>
    

    胸腺素3

    使用^{}对象的^{}方法:

    <div th:if="${#ctx.containsVariable('myVariable')}" th:text="Yes, $myVariable exists!"></div>
    
  4. # 4 楼答案

    可以使用条件运算符。如果存在或为空字符串,则将写入变量:

    <p th:text="${variable}?:''"></p>