2017-08-31 73 views
0

我有一个Springboot & Thymeleaf项目在我的人物输入中生成相同的“名称”。Thymeleaf和Springboot项目 - 标签名称

控制器看起来像:

@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" 

回答

1

您错用了th:field属性。

其目的是将您的输入与form-b​​acking bean中的属性绑定。所以,你应该可以创建单独的形式为每个对象,并用它在以下方式:

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

...或者创建一个表单,支持豆,这将结合你的对象既,如:

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属性必须选择表达式(*{...}), 这是有道理的给定的事实,他们将在 形式,支持豆,而不是在上下文变量进行评估(或Spring MVC术语中的模型 属性)。