Rey Libutan
Rey Libutan

Reputation: 5314

Thymeleaf: th:text only if not null?

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>

Upvotes: 0

Views: 16594

Answers (4)

Devraj Giri
Devraj Giri

Reputation: 21

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>

Upvotes: 0

Sarvar Nishonboyev
Sarvar Nishonboyev

Reputation: 13080

Try this code, it is more optimal:

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

? - checks if the resource is not null

Upvotes: 3

Aeseir
Aeseir

Reputation: 8414

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>

Upvotes: 3

anishroniyar
anishroniyar

Reputation: 96

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>

Upvotes: 0

Related Questions