Thymeleaf: th:text only if not null?

帅比萌擦擦* 提交于 2020-01-03 05:42:06

问题


I have something like below, which of course works if user had previously input his wrong credentials.

However if I directly go to my login fail url /login?error for example without any previous incorrect logins, session[SPRING_SECURITY_LAST_EXCEPTION] is of course null and I get a nasty 404.

<span th:text="${session[SPRING_SECURITY_LAST_EXCEPTION].message}">Invalid credentials</span>

Question:

Is there a processor for something like below (which is too long to write and read most of the time), or should I just roll my own?

<span th:text="${session[SPRING_SECURITY_LAST_EXCEPTION] != null ? session[SPRING_SECURITY_LAST_EXCEPTION].message : #messages.msg('AbstractUserDetailsAuthenticationProvider.badCredentials')}">
    Invalid credentials
</span>

回答1:


You can use the th:if statement:

<span th:if="${session[SPRING_SECURITY_LAST_EXCEPTION].message}" th:text="${session[SPRING_SECURITY_LAST_EXCEPTION].message}">Invalid credentials</span>

That will only display this line if there is a value present.

EDIT 1:

Extra check:

<span th:if="${session[SPRING_SECURITY_LAST_EXCEPTION] != null and session[SPRING_SECURITY_LAST_EXCEPTION].message != null}" th:text="${session[SPRING_SECURITY_LAST_EXCEPTION].message}">Invalid credentials</span>



回答2:


Try this code, it is more optimal:

${session['SPRING_SECURITY_LAST_EXCEPTION']?.message}

? - checks if the resource is not null




回答3:


Try this:

<span th:if="${session[SPRING_SECURITY_LAST_EXCEPTION].message != null}">
    <span th:text="${session[SPRING_SECURITY_LAST_EXCEPTION].message}">Invalid credentials</span>
</span>



回答4:


In your controller set the null string variable as

String nullvalue="";
model.addAttribute("nullvalue",nullvalue);
model.addAttribute("entity",entity);

then in your view class as in thymeleaf

<td data-th-if="${entity.field != nullvalue}">ok</td>


来源:https://stackoverflow.com/questions/31524073/thymeleaf-thtext-only-if-not-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!