我有一个 person 类和一个 personList DTO。DTO 用于将人员对象列表绑定到视图。用户可以编辑一个或多个人,然后单击保存以一次保存所有这些人的编辑。现在我想验证新输入。问题是控制器代码“bindingResults.hasErrors()”没有返回用户输入错误。我认为这是因为中间有 personList DTO。似乎它只是检查 personList 类中的错误,而不是像它应该的那样检查 person 类中的错误。如何解决?
模型
public class Person implements Serializable{
private static final long serialVersionUID = 1L;
@NotEmpty(message="Name must be filled.")
private String name;
@Min(value=1900, message="Year is invalid")
@Max(value=2100, message="Year is invalid")
private int year;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
}
DTO
public class PersonList {
private List<Person> personList;
public List<Person> getPersonList() {
return personList;
}
public void setPersonList(List<Person> personList) {
this.personList = personList;
}
}
看法
<form action="person" method="post" th:object="${personListBind}">
<th:block th:each="person, itemStat : *{personList}">
Name:
<input type="text" th:field="*{personList[__${itemStat.index}__].name}" />
Year:
<input type="text" th:field="*{personList[__${itemStat.index}__].year}" />
</th:block>
<input type="submit" name="btnSaveEdit" value="Save"/>
控制器
@RequestMapping(value = "/person", method = RequestMethod.POST)
public ModelAndView editPerson(
@Valid @ModelAttribute PersonList personList,
BindingResult bindingResults) {
if(bindingResults.hasErrors()){
//perform action
}
找到了解决方案。一个简单的改变。只需要在 DTO 类中添加 @Valid 即可。这是唯一需要更新的行: private List<@Valid Person> personList;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句