简体   繁体   中英

Not able to bind form variables to ModelAttribute annotated variable in Spring MVC

I have a form :

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

And a method in the controller which the form posts to

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

I also have a class Student1 like this

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

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

The code is written in Groovy

My understanding is that when the form is submitted spring mvc will create a Student1 object based on the values in the form and then bind the values from the form to the properties of the Student1 object

The example does not work. What is incorrect about my understanding ? Or what mistake am i making in the example above ?

the mistake was using student1.firstName instead of firstName

if i change my form to what looks below then the ModelAttribute annotation does the binding properly

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM