首页 > 解决方案 > 同一页面中有多个相似的表单

问题描述

在带有 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 和来自两个表单的字段之间的干扰。

一种解决方案是拥有两个模型,FatherMother使用诸如fatherFirstName确保没有重复的 HTML ID 的字段命名。但这会导致大量代码重复,以及长且不同的字段名称(而只有 HTML ID 需要不同)。

如何解决?有没有办法告诉 Spring 为 id 加上一些字符串前缀,同时确保我仍然可以Person对这两种形式使用相同的模型?

标签: spring-bootthymeleaf

解决方案


推荐阅读