我的问题如下:
我必须从一个表单中填写 2 个不同的对象。
有了 1 个对象,我只需在 newFoo.html 中做:
<form th:object="${foo}" th:action="@{/foo}" method="post">
<input type="text" th:field="*{name}"/>
<button type="submit">Go</button>
</form>
在 FooController 中:
@RequestMapping(value = "/foo/new", method = RequestMethod.GET)
public String newFoo(final Foo foo, Model model) {
return "newFoo";
}
@RequestMapping(value = "/foo/new", method = RequestMethod.POST)
public String saveFoo(final Foo foo, final BindingResult bindingResult, Model model) {
fooService.save(foo);
return "redirect:/foo/new";
}
假设我有另一个对象栏,其中包含“状态”变量。如何传递该对象以便我可以在同一个表单中提交输入?
喜欢:
<form th:object="${foo} && ${bar}" th:action="@{/foo}" method="post">
<input type="text" th:field="*{name}"/>
<input type="text" th:field="*{status}"/>
<button type="submit">Go</button>
</form>
到目前为止,我尝试使用其中包含 th:object 的字段集,但不起作用,我尝试在表单中放入两个 th:object,这也不起作用。
我发现的唯一方法是构建一个包含这两个对象的另一个对象,然后传递它。这很好用,但我不能创建那种对象,这是胡说八道(即使它有效)。
当然,这里的对象并不像 Foo 和 Bar 那样简单,否则我会合并这两个。但这不是我能做的。
甚至可以传递两个这样的对象以在表单中使用吗?
已经谢谢了。
最佳答案
我认为您不需要使用两个 th:objects
。只需使用 th:value
<form th:action="@{/foo}" method="post">
<input type="text" th:value="${foo.name}" name="name"/>
<input type="text" th:value="${bar.status}" name="status"/>
<button type="submit">Go</button>
</form>
我认为 Spring 在 Controller 方面足够聪明,可以使用其映射技术将您的字段映射到其正确的命令对象 foo 或 bar。
关于java - 如何使用 thymeleaf 传递两个对象以在表单中使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16122257/