java - 如何使用 thymeleaf 传递两个对象以在表单中使用?

标签 java html spring thymeleaf

我的问题如下:

我必须从一个表单中填写 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/

相关文章:

java - 使用下面的java代码修改文件中特定位置的音频文件的音调

java - 尝试从数组写入对象时出现不可序列化异常

iphone - 在 iphone 应用程序中嵌入 HTML 页面的最佳框架?

java - 更改用户后 Hibernate 不运行

java - 如何将此代码从 Spring 转换为 Spring Boot?

java - Spring Boot Jackson 日期和时间戳格式

java - javafx 中代码区域的自动补全

javascript - 如何强制超链接显示打开/保存对话框而不是在浏览器中打开它?

javascript - 有什么办法可以强制所有带有标签的 Visjs 节点大小相同?

java - 在 Spring PetClinic 示例应用程序中映射 URL