【问题标题】:thymeleaf Property or field cannot be found on null在 null 上找不到 thymeleaf 属性或字段
【发布时间】:2017-02-22 05:43:23
【问题描述】:

如果${object} 为空,那么*{item} 访问的项目将导致:

org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'item' cannot be found on null

那么如何解决这个问题,我希望保留 div 结构,如下例所示,当currentUser 为空时,div 包含城市和名称仍然存在。

<div class="form" th:object="${currentUser}">
     <div class="form-group form-group-sm">
          <label>city:</label>
          <span id="details_city" th:text="*{address == null ? '' : address.city}">Hongkong</span>
     </div>
     <div class="form-group form-group-sm">
          <label>name:</label>
          <span id="details_username" th:text="*{name}">Jane</span>
     </div>
</div>

【问题讨论】:

    标签: thymeleaf


    【解决方案1】:

    我在一个项目中看到过这种情况(但不是春季项目)。该方法是所有用户,即使是匿名用户(未经过身份验证),都由 User(例如 CurrentUser)实例表示。对于匿名用户,此实例大部分为空。这个想法是摆脱空检查。 User 类中有一个专门的方法来回答所代表的用户是否经过身份验证。 IMO 这种方法在所使用的技术堆栈环境中运行良好。

    如果您的项目可行,您也可以尝试这个想法。您可以为匿名用户创建一个空的currentUser 实例。那么currentUser 永远不会为空。但是如果您使用 spring security + thymeleaf 安全方言,您可以使用 thymeleaf 来确定用户是否是匿名的(如果这是必要的)。例如。仅对登录用户可见的示例注销链接可能会呈现如下:

    <li sec:authorize="isAuthenticated()">
          <a href="#" class="log-out-link">
             <i class="fa fa-sign-out"></i> Log out
          </a>
    </li>
    

    @ControllerAdvice@ModelAttribute 可以在所有相关视图中推送用户表示。或者,您可以在视图中提供一个单独的空用户并使用类似th:object="${#objects.nullSafe(currentUser,emptyUser)}"

    如果这太多了,那么不要使用th:object 并添加一些额外的检查。

    【讨论】:

    • 当我尝试你的想法时我会回来的。 :)
    【解决方案2】:

    在我看来,你有两个选择:

    • 传递一个对象实例(字段为空值)或
    • 复制您的 div 结构,一个是 th:if="${object != null}",另一个是 th:if="${object == null}

    【讨论】:

      猜你喜欢
      • 2018-01-09
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 2016-04-11
      • 2018-03-31
      • 2018-08-07
      • 2016-11-16
      • 2018-05-04
      相关资源
      最近更新 更多