Spring Form标签创建值数组

时间:2019-05-02 05:44:47

标签: spring spring-mvc data-binding spring-form

我有一个简单的表格,用户可以从中选择一个值。我不确定它是如何工作的,但如果POJO类中的指向同一个字段的选择没有被覆盖,则两个值之间用逗号分隔。为什么会这样呢?幕后有任何String连接吗?

它看起来像这样:

<form:form action="processForm" modelAttribute="student">

        First Name : <form:input path="firstName"/>
        <br><br>
        Last Name : <form:input path="lastName"/>
        <br><br>
        Country : <form:select path="country">
                    <form:option value="Brazil" label="Brazil" />
                    <form:option value="France" label="France" />
                    <form:option value="Germany" label="Germany"></form:option>
                    <form:option value="India" label="India"></form:option>
                    <form:option value="" label="Select" />
                </form:select>
        <br><br>
        Country : <form:select path="country">
                    <form:options items="${student.countryOptions}" />
                </form:select>
        <br><br>
        <input type="submit" value="Submit">

    </form:form>

enter image description here

@Controller
@RequestMapping("/student")
public class StudentController {

    @Value("#{countryOptionsID}")
    private Map<String, String> countryOptionsProperties;

    @Value("#{favoriteLanguageID}")
    private Map<String, String> favoriteLanguageProperties;

    @RequestMapping("/showForm")
    public String showForm(Model theModel) {

        theModel.addAttribute("student", new Student());
        // add the country options to the model
        theModel.addAttribute("theCountryOptions", countryOptionsProperties);
        theModel.addAttribute("theFavoriteLanguageOptions", favoriteLanguageProperties);
        return "student-form";
    }

    @RequestMapping("/processForm")
    public String processForm(@ModelAttribute("student") Student theStudent) {
        System.out.println("Student Details : " + theStudent);
        return "student-confirmation";
    }

    @RequestMapping("/processFormA")
    public String processFormA(Student student) { //without using @ModelAttribute
        System.out.println("without using @ModelAttribute Student Details : " + student);
        return "student-confirmation";
    }

}

和属性类似:

BR=Brazil
FR=France
CO=Colombia
IN=India
LK=Sri Lanka

1 个答案:

答案 0 :(得分:0)

如果您在控制器中填写模型:

theModel.addAttribute("theCountryOptions", countryOptionsProperties);

这意味着在视图中您可以获取该对象:

Country : 
<form:select path="country">
    <form:options items="${theCountryOptions}" />
</form:select>