Search code examples
springjspspring-mvcthymeleaf

How to make thymeleaf to ignore the null object?


I have a spring mvc project project with jsp as view. I need to use thymeleaf now. The old jsp project will auto ignore the manager object, if I don't put the manager object to the ModelMap.

  <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>

However Thymeleaf will give a error if I write as

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

I knew we can check the object as

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

Do I have to writte check each of them ?


Solution

  • There is a safe navigation & an elvis operator in Spring EL which you can use in Thymeleaf. Here is the docs which describes it. Use it like below in your case which will return null instead of throwing an exception.

    ${manager?.email}