【发布时间】:2020-01-23 10:28:22
【问题描述】:
我正在使用 Spring Boot (v2.0.1.RELEASE)。我在 HTML 模板中遇到问题,尝试将表单中的 2 个不同对象发送到控制器。除两者的 ID 属性外,所有属性表单对象均已成功发送。两者都有一个名为 ID 的字段,当到达控制器时会被覆盖。
这就是 HTML 中的表单:
<form action="#" th:action="@{/test}" method="post" class="form floating-label">
<div class="form-group">
<!-- TEST VARIABLES -->
<input type="text" th:field="${test.id}" class="form-control"/>
<input type="text" th:field="${test.nombre}" class="form-control"/>
<input type="text" th:field="${test.formatotest.id}" class="form-control"/>
<input type="text" th:field="${test.formatotest.nombre}" class="form-control"/>
<input type="text" th:field="${test.activo}" class="form-control"/>
<!-- USER VARIABLES-->
<input type="text" th:field="${user.id}" class="form-control"/>
<input type="text" th:field="${user.email}" class="form-control"/>
<input type="text" th:field="${user.username}" class="form-control"/>
</div>
<div>
<input type="submit" value="Send" class="btn btn-primary btn-raised" />
</div>
<br>
</form>
控制器功能:
@PostMapping("/test")
public ModelAndView showTest(Test test, User user) {
System.out.println(" * User ID: ["+user.getId()+"] Test ID:["+test.getId()+"]");
ModelAndView testModel = new ModelAndView("test");
testModel.addObject("user",user);
testModel.addObject("test",test);
return testModel;
}
当我打印两个 ID 时,它们都显示相同。我尝试使用 th:value, name nad id 而不是 th:field 仍然失败。
HTML 表单的第二次尝试:
<form action="#" th:action="@{/test}" method="post" class="form floating-label">
<div class="form-group">
<!-- TEST VARIABLES -->
<input type="hidden" th:value="${test.id}" name="id" id="id" class="form-control"/>
<input type="hidden" th:value="${test.nombre}" name="nombre" id="nombre" class="form-control"/>
<input type="hidden" th:value="${test.formatotest.id}" name="formatotest.id" id="formatotest.id" class="form-control"/>
<input type="hidden" th:value="${test.formatotest.nombre}" name="formatotest.nombre" id="formatotest.nombre" class="form-control"/>
<input type="hidden" th:value="${test.activo}" name="activo" id="activo" class="form-control"/>
<!-- USER VARIABLES-->
<input type="hidden" th:value="${user.id}" name="id" id="id" class="form-control"/>
<input type="hidden" th:value="${user.email}" name="email" id="email" class="form-control"/>
<input type="hidden" th:value="${user.username}" name="username}" id="username" class="form-control"/>
</div>
<div>
<input type="submit" value="Send" class="btn btn-primary btn-raised" />
</div>
<br>
</form>
一个奇怪的细节是,这取决于我首先在 HTML 中输入的内容,这将成为他们两者的集合。
【问题讨论】:
-
当您尝试保留 th:field 但为 name 和 id 属性指定不同的值时会发生什么?例如 - 和
-
我试过了,它仍然是一样的,它会覆盖它。我读过一些东西,当使用 th:field 时,名称值和 id 被省略,并且在只有一个对象时使用。我真的迷路了……
-
在表单中,尝试添加 th:object="${test} && ${user}"
-
我试图像你说的那样在表单标签中添加 th:object="${test} && ${user}" ,它显示了该错误。 [org.thymeleaf.exceptions.TemplateProcessingException:无法解析为表达式:“${test} && ${user}”(模板:“index”-第 100 行,第 67 列)]。该注释不合法。
标签: spring spring-boot thymeleaf