我有一张表格:
<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对象的属性
该示例不起作用。我的理解有什么不对?或者我在上面的例子中犯了什么错误?
答案 0 :(得分:0)
错误是使用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>