Iam trying post a simple form to a spring controller using a thymeleaf. The backing bean includes a boolean value which is mapped to a checkbox in the template using th:field inside of a th:object tag. When I take a look at the rendered html DOM, spring mvc is adding an hidden input field, where the name is _attributeName. The name of the main input field is generated as attributeName. Now when Iam trying to post the form it aborts with a 400 because the request parameter _attributeName cant be mapped to a backing bean object (simply doesnt exist). So in addition the request wohld include attributeName as well as _attributeName. Why is this happening?
1
votes
2 Answers
5
votes
-2
votes
Tried solution mentioned by Vinc, but didn't work for me. However below worked for me.
Controller
@Controller
public class BaseController {
@GetMapping("/")
private String index(DemoDto demoDto){
return "index";
}
@PostMapping("/")
private String receiveValues(DemoDto demoDto) {
System.out.println(demoDto);
return "index";
}
}
DTO
public class DemoDto {
private String name;
private boolean global;
//getter setter for name
public boolean isGlobal() {
return global;
}
public void setGlobal(boolean global) {
this.global = global;
}
//toString()
}
HTML
<body>
<form th:action="@{/}" th:method="post" th:object="${demoDto}">
<label>Enter Name:</label>
<input type="text" th:field="*{name}" name="name">
<br/>
<label>Global</label>
<input type="checkbox" th:field="${demoDto.global}"/>
<input type="submit" value="Submit">
</form>
</body>
Here most important is how you define th:field="${demoDto.global}". Both $ as well as object name demoDto are required here.
Generated html code will be.
<body>
<form action="/" method="post">
<label>Enter Name:</label>
<input type="text" name="name" id="name" value="">
<br/>
<label>Global</label>
<input type="checkbox" id="global1" name="global" value="true"/>
<input type="hidden" name="_global" value="on"/>
<input type="submit" value="Submit">
</form>
</body>
When submitted from ui received:
DemoDto [name=Dev, global=true]