【问题标题】:Thymeleaf and Springboot project - tag namesThymeleaf 和 Spring Boot 项目 - 标记名称
【发布时间】:2017-08-31 06:20:42
【问题描述】:

我有一个 Springboot 和 Thymeleaf 项目,它在我的个人输入中生成相同的“名称”。

控制器看起来像:

    @GetMapping("/newEpisode")
public String episodeForm(Model model) {
    model.addAttribute("episode", new Episode());
    List<Country> countries = countryRepository.findAll();
    Set<String> roles = new HashSet<>();
    roles.add("Admin");
    model.addAttribute("primaryPerson1",new EpisodePerson());
    model.addAttribute("primaryPerson2",new EpisodePerson());
    model.addAttribute("roles", roles);
    model.addAttribute("countries", countries);
    return "episode";
}

我的一些 HTML 看起来像:

<input type="text" class="form-control person surname" style="text-transform: uppercase" data-property="surname" placeholder="SURNAME" th:field="${primaryPerson1.person.surname}"/>

但是在 HTML 中为这个标签生成的名字不是唯一的:

<input type="text" class="form-control person surname" style="text-transform: uppercase" data-property="surname" id="surname1" placeholder="SURNAME" name="person.surname" value="">

为什么 html 中的所有人员标签都共享相同的名称,例如我有两个:

name="person.surname"

【问题讨论】:

    标签: html spring spring-boot thymeleaf


    【解决方案1】:

    您误用了th:field 属性。

    其目的是将您的输入与表单支持 bean 中的属性绑定。因此,您应该为每个对象创建单独的表单并以下列方式使用它:

    <!-- Irrelevant attributes omitted -->
    <form th:object="${primaryPerson1}">
        <input th:field="*{person.surname}"/>
    </form>
    

    ...或创建一个表单支持 bean,它将结合您的两个对象,例如:

    public class EpisodeFormBean {
    
        private List<EpisodePerson> episodePersons;
    
        //getter and setter omitted
    }
    

    ...然后将其添加到您的 episodeForm 方法中的模型...

    EpisodeFormBean episodeFormBean = new EpisodeFormBean();
    episodeFormBean.setEpisodePersons(Arrays.asList(new EpisodePerson(), new EpisodePerson()));
    model.addAttribute("episodeFormBean", episodeFormBean);
    

    ...并在您的模板中使用它,如下所示:

    <!-- Irrelevant attributes omitted -->
    <form th:object="${episodeFormBean}">
        <input th:field="*{episodePersons[0].person.surname}"/>
        <input th:field="*{episodePersons[1].person.surname}"/>
    </form>
    

    在第二种解决方案中,生成的名称将是唯一的。我认为它更适合您的需求。

    您应该查看Tutorial: Thymeleaf + Spring,因为那里有很好的解释。特别是你应该注意到一个短语:

    th:field 属性的值必须是选择表达式 (*{...}), 这是有道理的,因为他们将在 form-b​​acking bean而不是上下文变量(或模型 Spring MVC 术语中的属性)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-16
      • 1970-01-01
      • 2016-11-30
      • 1970-01-01
      • 1970-01-01
      • 2020-11-07
      • 2019-10-31
      • 2021-08-02
      相关资源
      最近更新 更多