How to get Thymeleaf to parse boolean for SpringBootMVC? [ThymeLeaf-SpringBoot-Java17]

Issue

So I have a hardcoded true/false value in HTML so I can use that to fill the E.bool value for one of my entities after the HTML form submits (POST).

HTML

// I tried
<select id="isBool" name="isBool" class="form-select" aria-label="select">
  <option value="1">true option</option>
  <option value="0">false option</option>
</select>
// then I tried
<select id="isBool" name="isBool" class="form-select" aria-label="select">
  <option th:value="1">true option</option>
  <option th:value="0">false option</option>
</select>
// then I tried
<select id="isBool" name="isBool" class="form-select" aria-label="select">
  <option th:value="${true}">true option</option>
  <option th:value="${false}">false option</option>
</select>

Entity

@Entity
@Table
public class E {
  ..
  @Column
  boolean bool
  ..
}

Controller

public String addE(@Valid E e, BindingResult result, HttpServletRequest request, Model model) {
  ...
  // no matter what, E has bool = false here :(
  ...
}

What am I doing wrong? No matter what I try, it’s always false.

The craziest thing is that I can literally go to my IntelliJ and see in the debugger, that the request.parameters has the correct value right there! What’s going on? Why is ThymeLeaf/Spring being so difficult? Is there any easier way to get a boolean like this through the controller?

paramter value

Solution

Amazingly, it was the getters fault for the boolean member field. My IDE generated it as "isBool" instead of "getBool" and apparently Thymeleaf only looks for literal getters and setters.

Answered By – hello

Answer Checked By – David Goodson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.