I'am trying to "send" a "complex" object from a thymeleaf form back to the controller. I found this minimal example (Send datas from html to controller in Thymeleaf?), which does basically the same thing (Works perfectly). The only difference is, that their object has a String attribute instead of an other object.
But once I replace the String Attribute with the bar object, the bar object is always null, when submitting the form. Is submitting nested objects even possible?
Objects
public class Foo {
private Bar bar;
public Bar getBar() {
return bar;
}
public void setBar(Bar bar) {
this.bar = bar;
}
}
public class Bar {
private String id;
public Bar(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
Controller
@RequestMapping(value = "/showForm", method= RequestMethod.GET)
public String showForm(Model model) {
Foo foo = new Foo();
foo.setBar(new Bar("test"));
model.addAttribute("foo", foo);
return Pages.TEST;
}
@RequestMapping(value = "/processForm", method=RequestMethod.POST)
public String processForm(@ModelAttribute(value="foo") Foo foo) {
...
return Pages.TEST;
}
HTML
<form action="#" th:action="@{/processForm}" th:object="${foo}" method="post">
<input type="text" th:field="*{bar}"/>
<input type="submit"/>
</form>
You have to bind your input text to id
field of bar
object.
<form action="#" th:action="@{/processForm}" th:object="${foo}" method="post">
<input type="text" th:field="*{bar.id}"/>
<input type="submit"/>
</form>