【发布时间】:2020-12-06 22:53:54
【问题描述】:
我正在使用下面的代码将来自列表的内容绑定到视图。 这是人员对象的列表。这个人对象有一个数字字段(年份)。 有时数据库中年份字段的内容为零。 发生这种情况时,它将在表单的输入字段上绑定零。 相反,我想绑定一个空字符串。 也就是说,只需将该字段留空,而不是显示数字零。 我怎么做? 显然,当有实际年份时,它应该继续显示年份。
型号
@Entity
public class Person implements Serializable{
private static final long serialVersionUID = 1L;
private String name;
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;
}
}
控制器
@RequestMapping(value = "/person", method = RequestMethod.POST)
public ModelAndView editPerson(@ModelAttribute PersonList personList)
{
//perform operations
//display results
ModelAndView modelAndView = new ModelAndView("Person.html");
modelAndView.addObject("personListBind", personList);
return modelAndView;
}
查看
<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>
【问题讨论】:
标签: java spring-mvc thymeleaf