Thymeleaf - How to compare string with request parameter in html in Thymeleaf tag "th:if"?
59,177
Solution 1
It's not working because param.error
is array of strings. You must retrieve first element of array (param.error[0]
) to get first value of parameter (see documentation). Besides that you can access request parameter via Web context object method #httpServletRequest.getParameter
that returns first value when parameter is multivalued (see documentation).
-
Usage of Web context namespaces for request attributes
<div class="error" th:if="${param.error[0] == 'badCredentialsException'}" th:with="errorMsg=#{login.badCredentials}"> <p class="errorMsg"><span th:text="${errorMsg}"></span></p> </div>
-
Usage of Web context object
<div class="error" th:if="${#httpServletRequest.getParameter('error') == 'badCredentialsException'}" th:with="errorMsg=#{login.badCredentials}"> <p class="errorMsg"><span th:text="${errorMsg}"></span></p> </div>
Solution 2
With Thymeleaf 3, I normally use #request
(a short form of #httpservletrequest
) and #strings.equals()
for that, which will look like this:
<div th:if="${#strings.equals(#request.getParameter('error'), 'badCredentialsException')}"></div>
Author by
user3515080
Updated on August 08, 2021Comments
-
user3515080 almost 3 years
How to compare string with request parameter in html in Thymeleaf tag "th:if" ? right now i am using this
<div class="error" th:if="${param.error == 'badCredentialsException'}" th:with="errorMsg=#{login.badCredentials}"> <p class="errorMsg"><span th:text="${errorMsg}"></span></p> </div>
But no luck, it is not working.
-
Gondy over 8 yearsImportant note about this: ${param.error[0]} will cause SpelEvaluationException Cannot index into a null value if there will be no such request parameter. It depends on you context, but you may want check ${param.containsKey('error')} before.
-
Eric Aya almost 3 yearsThis is the same solution as in this other answer.