spring-boot - 同一页面中有多个相似的表单
问题描述
在带有 Thymeleaf 的 Spring Boot 中,我有一个页面应该处理对应于同一模型的两种表单Person
。每个表单都可以单独提交,所以我在控制器中使用了两种方法:
@PostMapping(value="/", params={"submitFather"})
public String submitFather(
@ModelAttribute("fatherForm") Person fatherForm,
@ModelAttribute("motherForm") Person motherForm,
Model model) {
// ... Process fatherForm
// Return the updated page
model.addAttribute("fatherForm", fatherForm);
model.addAttribute("motherForm", motherForm);
return "index.html";
}
@PostMapping(value="/", params={"submitMother"})
public String submitMother(
@ModelAttribute("fatherForm") Person fatherForm,
@ModelAttribute("motherForm") Person motherForm,
Model model) {
// ... Process motherForm
// Return the updated page
model.addAttribute("fatherForm", fatherForm);
model.addAttribute("motherForm", motherForm);
return "index.html";
}
在我的模板中:
<form id="fatherForm" th:object="${fatherForm}" method="post">
<label for="firstName">First name</label>
<input type="text" th:field="*{firstName}"><br>
<!-- ... other Person fields -->
<input type="submit" name="submitFather" value="Order">
</form>
<form id="motherForm" th:object="${motherForm}" method="post">
<label for="firstName">First name</label>
<input type="text" th:field="*{firstName}"><br>
<!-- ... other Person fields -->
<input type="submit" name="submitMother" value="Order">
</form>
我遇到的问题是这会导致 HTML ID 冲突。例如,将有两个<input>
id firstName
。这会在提交时导致无效的 HTML 和来自两个表单的字段之间的干扰。
一种解决方案是拥有两个模型,Father
并Mother
使用诸如fatherFirstName
确保没有重复的 HTML ID 的字段命名。但这会导致大量代码重复,以及长且不同的字段名称(而只有 HTML ID 需要不同)。
如何解决?有没有办法告诉 Spring 为 id 加上一些字符串前缀,同时确保我仍然可以Person
对这两种形式使用相同的模型?
解决方案
推荐阅读
- javascript - 提供的 JavaScript 文件为空白
- android - 如何组合 ACTION_SEND 和 ACTION_VIEW 意图类型?
- php - 如何在不刷新的情况下提交表单?
- vba - 在 Outlook VBA 中提取 getTable() 收件人电子邮件地址的最快方法
- azure-devops - 依赖于私有 AZ 存储库的 Azure 构建管道
- c# - 从带有标头值的 SOAP 响应中解析 C# 中的 XML
- jquery - Jquery and Twig - 在 jquery 中操作设置的树枝数组
- c# - 为什么接收 API 没有获取参数中的内容?
- java - 在双向映射的情况下如何在spring-data-jpa中删除
- postgresql - PostgreSQL 在选择查询中转义 Microsoft 特殊字符