繁体   English   中英

Thymeleaf和Springboot项目-标签名称

[英]Thymeleaf and Springboot project - tag names

我有一个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"

您滥用了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>

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

您应该查看教程:Thymeleaf + Spring,因为那里有很好的解释。 特别是您应该注意以下短语:

th:field属性的值必须是选择表达式( *{...} ),考虑到它们将在表单支持Bean而不是上下文变量(或Spring MVC行话中的模型属性)中进行评估,这是有道理的)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM