【问题标题】:Not able to bind form variables to ModelAttribute annotated variable in Spring MVC无法将表单变量绑定到 Spring MVC 中的 ModelAttribute 注释变量
【发布时间】:2016-08-15 13:35:02
【问题描述】:

我有一个表格:

<form action="modelattributebinding" method="post">
    <input name = "student1.firstName" value = "Michael">
    <input name = "student1.lastName"  value="Jackson" >
    <input name="student1.age" value="34">
    <input name="student1.hobby" value="music">
    <input type="submit">   
</form>

以及表单发布到的控制器中的方法

@RequestMapping(value = "/modelattributebinding" , 
         method = RequestMethod.POST)
public ModelAndView binding(@ModelAttribute("student1")Student1 student1){      
    println student1.getFirstName()
    null        
}

我也有一堂这样的Student1

public  class Student1{
    String firstName
    String lastName
    int age
    String hobby

    @Override
    public String toString() {
        "firstName $firstName , lastName $lastName"
    }

代码是用 Groovy 编写的

我的理解是,当提交表单时,spring mvc会根据表单中的值创建一个Student1对象,然后将表单中的值绑定到Student1对象的属性上

该示例不起作用。我的理解有什么不正确的?或者我在上面的例子中犯了什么错误?

【问题讨论】:

    标签: forms spring-mvc modelattribute


    【解决方案1】:

    错误是使用 student1.firstName 而不是 firstName

    如果我将表单更改为如下所示,则 ModelAttribute 注释会正确绑定

    <form action="modelattributebinding" method="post">
        <input name = "firstName" value = "Michael">
        <input name = "lastName"  value="Jackson" >
        <input name="age" value="34">
        <input name="hobby" value="music">
        <input type="submit">   
    </form>
    

    【讨论】:

      猜你喜欢
      • 2020-06-11
      • 1970-01-01
      • 2020-11-21
      • 2017-04-12
      • 2015-03-13
      • 2013-01-16
      • 1970-01-01
      • 2017-11-27
      • 2016-10-28
      相关资源
      最近更新 更多