【问题标题】:Spring form tag creates array of valuesSpring表单标签创建值数组
【发布时间】:2019-09-20 14:39:50
【问题描述】:

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

看起来像这样:

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

@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

【问题讨论】:

  • 看来你在控制器中做错了。你能显示你的控制器代码吗?
  • 嘿,我已经编辑了代码,请看一下:)
  • 你如何构造你的Student 对象?有一个 countryOptions 字段是一个键。
  • 现在呢?控制器及其方法一切正常。我的问题是为什么对来自 POJO 的一个文件执行的数据绑定将两个字符串合并为一个并用逗号分隔它

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


【解决方案1】:

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

theModel.addAttribute("theCountryOptions", countryOptionsProperties);

这意味着在视图中你可以得到这个对象:

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

【讨论】:

  • @Mateusz Gebroski 如果此答案对您有帮助,请接受。否则,请让我澄清并提供指向您应用程序仓库的链接或提供更多代码
猜你喜欢
  • 1970-01-01
  • 2022-01-24
  • 2011-06-27
  • 1970-01-01
  • 2013-02-22
  • 1970-01-01
  • 1970-01-01
  • 2019-07-20
  • 2019-10-17
相关资源
最近更新 更多