【问题标题】:How to make thymeleaf to ignore the null object?如何让百里香忽略空对象?
【发布时间】:2017-07-07 05:24:03
【问题描述】:

我有一个以jsp 为视图的spring mvc 项目。我现在需要使用百里香。如果我不将 manager 对象放入 ModelMap,旧的 jsp 项目将自动忽略 manager 对象。

  <form class="form-horizontal" method="post" action="<c:url value=" /${action} " />">
<input type="hidden" name="id" value="${manager.id}">
....
<div class="form-group">
    <label class="col-sm-2 control-label">email</label>
    <div class="col-sm-8">
        <input type="text" name="email" value="${manager.email}" class="form-control1" placeholder="Email">
    </div>
</div>
<div class="form-group">
    <label class="col-sm-2 control-label">phone</label>
    <div class="col-sm-8">
        <input type="text" name="mobile" value="${manager.mobile}" class="form-control1" placeholder="phone number">
    </div>
</div>
...
<div class="form-group">
    <div class="col-sm-8 col-sm-offset-2 ">
        <button class="btn btn-success1 btn-block">sumbit</button>
    </div>
</div>

</form>

但是如果我写成 Thymeleaf 会报错

     <input type="text" name="email" th:value="${manager.email}" class="form-control1" placeholder="Email">

我知道我们可以将对象检查为

<input type="text" name="mobile" th:value="${manager? manager.mobile : ''}" class="form-control1" placeholder="phone number">

我必须写检查他们每个人吗?

【问题讨论】:

    标签: spring jsp spring-mvc thymeleaf


    【解决方案1】:

    Spring EL 中有一个安全导航和一个 elvis 运算符,您可以在 Thymeleaf 中使用它们。这是docs 它描述了它。在您的情况下像下面这样使用它,它将返回 null 而不是抛出异常。

    ${manager?.email}
    

    【讨论】:

      猜你喜欢
      • 2019-06-01
      • 2018-04-25
      • 2017-02-27
      • 2017-04-28
      • 2016-07-29
      • 2021-01-25
      • 2019-08-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多