0

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> 

4 Answers 4

3

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> 
Sign up to request clarification or add additional context in comments.

4 Comments

if session[SPRING_SECURITY_LAST_EXCEPTION] is null, it will throw a n NPE on .message
Not the case, if it is null then if statement is FALSE therefore th:text doesn't get rendered.
This is what you wrote th:if="${session[SPRING_SECURITY_LAST_EXCEPTION].message}"
I've edited the answer to add another layer of tests just in case it doesn't work for you (which it did for me for a similar thing).
3

Try this code, it is more optimal:

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

? - checks if the resource is not null

1 Comment

This works and is nicely succinct! Is it documented anywhere? I don't see it in thymeleaf's docs.
0

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> 

Comments

0

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> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.