本文介绍了使用 thymeleaf 将表单数据发布到使用@ModelAttribute(复杂对象)的控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有 Element
类:
public class Element {
private Long id;
private Name name;
// Getters and Setters ...
}
还有 Name
类:
public class Name {
private String en;
private String fr;
private String de;
// Getters and Setters ...
}
有一个 getElementsController:
There is a getElementsController:
@GetMapping("/elements/create")
public String getElementsCreate() {
return "private/new-element";
}
有一个 NewElementController
控制器:
@PostMapping("/elements/create")
public String postElementsCreate(@ModelAttribute Element element) {
System.out.println(element)
return null;
}
有一个向 NewElementController 发送数据的表单:
There is a form that posts data to the NewElementController:
<form method="post" th:object="${element}" th:action="@{/elements/create}">
<input type="text" value="1" name="id" placeholder="Id"/>
// How should I make the input fields for:
element.name.en ?
element.name.fr ?
element.name.de ?
<button type="submit">Save element</button>
</form>
设置 Id 有效,但我无法访问 name
字段(它是一个对象)
我已经尝试过 th:field="*{name}"
和 th:field="*{name.en}"
,但它不起作用方式.
Setting the Id works, but I can not access the name
field (it is an object)
I have tried with th:field="*{name}"
and with th:field="*{name.en}"
, but it does not work in that way.
推荐答案
尝试以下操作:
<form method="post" th:object="${element}" th:action="@{/elements/create}">
<input type="text" name="id" th:value="*{id}" placeholder="Id"/>
<input type="text" name="name.en" th:value="*{name.en}" placeholder="Name (EN)"/>
<input type="text" name="name.fr" th:value="*{name.fr}" placeholder="Name (FR)"/>
<input type="text" name="name.de" th:value="*{name.de}" placeholder="Name (DE)"/>
<button type="submit">Save element</button>
</form>
你的 GET 控制器方法应该是这样的:
Yor controller method for GET should be like this:
@GetMapping("/elements/create")
public String getElementsCreate(Model model) {
Element element = new Element();
Name name = new Name();
element.setName(name);
model.addAttribute("element", element);
return "private/new-element.html";
}
这篇关于使用 thymeleaf 将表单数据发布到使用@ModelAttribute(复杂对象)的控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!