java—如何在SpringMVC中为int字段绑定空字符串而不是零?

b1payxdu  于 2021-07-03  发布在  Java
关注(0)|答案(2)|浏览(257)

我使用下面的代码将来自列表的内容绑定到视图。这是个人物品的清单。此person对象有一个数字字段(年份)。有时数据库中年份字段的内容为零。当这种情况发生时,它在表单的输入字段上绑定零。相反,我想绑定一个空字符串。也就是说,只需将字段留空,而不显示数字0。我该怎么做?显然,当有一个实际年份时,它应该继续显示年份。
模型

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

wtzytmuj1#

如果我理解正确的话,这些方法应该对你有用。

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<input type="text" th:if="${year eq 0}" value="No year">
<input type="text" th:unless="${year eq 0}" th:value="${year}">

</body>
</html>
flvlnr44

flvlnr442#

一种方法是使用派生值方法,以便ui将字段视为字符串。
模型

@Entity
public class Person implements Serializable {

    // all members from question are here, including getYear() and setYear()

    @Transient // Not a database column
    public String getYearStr() {
        return (year == 0 ? "" : Integer.toString(year));
    }

    public void setYearStr(String yearStr) {
        this.year = (yearStr.isEmpty() ? 0 : Integer.parseInt(yearStr));
    }

}

看法

Year:
    <input type="text" th:field="*{personList[__${itemStat.index}__].yearStr}" />

相关问题