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