Search code examples
htmlcastingthymeleafspring-el

Cast String to Long in SpringEL expression for th select


I am using an object's ID being in a list to decide if it should be selected, like so:

<option th:each="tag : ${tagList}" th:value="${tag.id}" th:text="${tag.text}" th:selected="${idSet.contains(tag.id)}"></option>

However, I have to specially create the idSet (Set<Long>), as my original implementations, using an existing Set<String>:

<option th:each="tag : ${tagList}" th:value="${tag.id}" th:text="${tag.text}" th:selected="${searchSet.contains(Long.valueOf(tag.id))}"></option>

OR

<option th:each="tag : ${tagList}" th:value="${tag.id}" th:text="${tag.text}" th:selected="${searchSet.contains(Long.parseLong(tag.id))}"></option>

Yielded this exception:

Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1011E: Method call: Attempted to call method valueOf(java.lang.Long) on null context object

How do I use my existing set of strings with a long in a SpringEL expression?


Solution

  • The special 'T' operator can be used to specify an instance of java.lang.Class (the 'type'). Static methods are invoked using this operator as well

    parseLong(String) is a static method of Long

    So this should work

    T(Long).parseLong(...)