首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Thymeleaf和Springboot项目-标记名称

Thymeleaf和Springboot项目-标记名称
EN

Stack Overflow用户
提问于 2017-08-31 14:20:43
回答 1查看 369关注 0票数 0

我有一个Springboot & Thymeleaf项目,它在我的person输入上生成相同的“名称”。

控制器看起来像这样:

代码语言:javascript
复制
    @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看起来像这样:

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

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

代码语言:javascript
复制
<input type="text" class="form-control person surname" style="text-transform: uppercase" data-property="surname" id="surname1" placeholder="SURNAME" name="person.surname" value="">

为什么html中的所有person标记都具有相同的名称?例如,我有两个:

代码语言:javascript
复制
name="person.surname"
EN

回答 1

Stack Overflow用户

发布于 2017-09-01 09:58:38

您误用了th:field属性。

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

代码语言:javascript
复制
<!-- Irrelevant attributes omitted -->
<form th:object="${primaryPerson1}">
    <input th:field="*{person.surname}"/>
</form>

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

代码语言:javascript
复制
public class EpisodeFormBean {

    private List<EpisodePerson> episodePersons;

    //getter and setter omitted
}

...then将其添加到episodeForm方法中的模型中...

代码语言:javascript
复制
EpisodeFormBean episodeFormBean = new EpisodeFormBean();
episodeFormBean.setEpisodePersons(Arrays.asList(new EpisodePerson(), new EpisodePerson()));
model.addAttribute("episodeFormBean", episodeFormBean);

...and在模板中使用它,如下所示:

代码语言:javascript
复制
<!-- 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属性的

值必须是选择表达式(*{...}),这是有意义的,因为它们将在表单支持bean上求值,而不是在上下文变量(或Spring MVC术语中的模型属性)上求值。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45974554

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档