将java枚举值绑定到Spring表单标记输入

时间:2015-12-08 23:14:36

标签: forms spring-mvc enums bind formatter

我想将我的枚举值绑定到Spring表单标记输入。我有整个过程的以下代码:

public enum Gender {
    MALE("M"),
    FEMALE("F");

    private String abbreviation;

    Gender (String abbreviation) {
        this.abbreviation = abbreviation;
    }

    public String getAbbreviation () {
        return abbreviation;
    }

    public static Gender getGenderEnum (String abbreviation) {
        Gender gender = null;

        if (abbreviation.equals("F"))
            gender = Gender.FEMALE;
        else
            gender = Gender.MALE;

        return gender;
    }

}

我的性别格式化程序和转换器:

public class GenderEnumFormatter implements Formatter<Gender> {

    @Override
    public String print(Gender gender, Locale locale) {
        return gender.getAbbreviation();
    }

    @Override
    public Gender parse(String genderString, Locale locale)
            throws ParseException {
        return Gender.getGenderEnum(genderString);
    }

}  

public class GenderEnumConverter implements Converter<String, Gender> {

    @Override
    public Gender convert(String source) {
        return Gender.getGenderEnum(source);
    }

}

我也在我的WebMvcConfigurerAdapter类中注册了我的转换器和格式化程序:

registry.addConverter(String.class, Gender.class,
            new GenderEnumConverter());
registry.addFormatter(new DistanceEnumFormatter());

以下是调用编辑表单的控制器方法:

@RequestMapping(value = "/edit/{id}")
public String showEditForm(Model model, @PathVariable long id) {
    model.addAttribute("race", raceRepository.findOne(id));

    return "raceEditForm";
}

以下是使用Spring表单标记的jsp的代码:

<form:form method="put" action="${edit_race_url}" commandName="race">
    <legend>Add a race</legend>
    <form:hidden path="id"/>
    <p>
        <label for="name">Race name: </label>
        <form:input id="name" path="name" />
    </p>
    <p>
        <label for="description">Race description: </label>
        <form:input id="description" path="description" />
    </p>
    <p>
        <label for="distance">Race distance: </label>
        <form:select id="distance" path="distance"
            items="${distances}" />
    </p>
    <p>
        <label for="gender">Race gender: </label>
        <form:select id="gender" path="gender"
            items="${genders}" />
    </p>
    <p>
        <label for="raceDate">Race date: </label>
        <form:input id="raceDate" path="raceDate"/>
    </p>
    <p id="buttons">
        <input id="reset" type="reset" tabindex="4"> <input
            id="submit" type="submit" tabindex="5" value="Update race">
    </p>
</form:form>

每当我保存一个新的Race时,从form:input到Gender和Distance枚举的转换都可以。但是当我想编辑将种族对象添加到模型属性的种族对象时,选择元素不会使用种族对象的当前距离和性别值进行更新,所有其他字段都会被当前填充种族对象的变量值。

我是否需要在某处包含InitBinder方法?感谢...

0 个答案:

没有答案