Fix Thymeleaf null boolean error (SpEL issue)
Problem: Thymeleaf null boolean error
You may encounter this error when rendering a Thymeleaf template:
cannot convert from null to boolean
This often appears only for specific users, such as test accounts or newly created data.
Environment
- Spring Boot
- Thymeleaf
- Spring Expression Language (SpEL)
Root Cause
The issue comes from how SpEL evaluates logical expressions.
Consider this code:
th:value="${cmpyNo == null or isWonmaster ? '' : cmpyNo}"
If isWonmaster is null, the expression becomes:
true OR null
SpEL does not allow null in logical operations. Both operands must be boolean.
Solution
1. Make the expression null-safe
th:value="${cmpyNo == null or isWonmaster == true ? '' : cmpyNo}"
or
th:value="${cmpyNo == null or (isWonmaster ?: false) ? '' : cmpyNo}"
2. Fix it at the Controller level (recommended)
Normalize the value before passing it to the view:
model.addAttribute("isWonmaster",
Boolean.TRUE.equals(user.getIsWonmaster()));
Then your template can safely use:
th:value="${cmpyNo == null or isWonmaster ? '' : cmpyNo}"
Why it only happens sometimes
This bug only occurs when the value is null:
|Value|Result| |---|---| |true|OK| |false|OK| |null|ERROR|
That’s why it often slips through testing and appears in edge cases.
Best Practice
- Always assume
Booleancan be null - Never use it directly in logical expressions
- Normalize it before evaluation
Recommended patterns:
isFlag == true
isFlag ?: false
Takeaway
This is not a Thymeleaf bug but a SpEL design constraint.
The most robust solution is:
- eliminate null at the Controller layer
- keep templates simple and predictable