我正在学习
Spring MVC,我到处寻找一个基本的控制器来查看数据绑定,但我没有尝试过任何工作.我可以将视图发布回控制器,我可以在那里看到带有属性的pojo,但每当我尝试将该对象添加到模型时,我什么也得不到.这是我到目前为止:
调节器
@Controller public class HomeController { @RequestMapping(value = "/",method = RequestMethod.GET) public String home(Model model) { model.addAttribute(new Person()); return "home"; } @RequestMapping(value="/about",method=RequestMethod.POST) public void about(Person person,Model model) { model.addAttribute("person",person); } }
我要绑定的类
public class Person { private String _firstName; private String _lastName; private Date _Birthday; //Set public void setFirstName(String FirstName){this._firstName = FirstName; } public void setLastName(String LastName){this._lastName= LastName; } public void setBirthDate(Date BirthDate){ this._Birthday = BirthDate;} //get public String getFirstName(){return _firstName;} public String getLastName(){return _lastName;} public Date getBirthDate(){return _Birthday;} }
查看 – 控制器到表单!工作
<Meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /> <html> </head> <body> FirstName: ${model.person.getFirstName} LastName: ${model.person.getLastName} </body> </html>
我可以或需要做什么才能让它绑定?
解决方法
模型属性是您在这里缺少的东西.
@Controller public class HomeController { @modelattribute("person") public Person getPerson(){ return new Person(); } @RequestMapping(value = "/",method = RequestMethod.GET) public String home() { return "home"; } @RequestMapping(value="/about",method=RequestMethod.POST) public void about(@modelattribute("person") Person person,BindingResult result,Model model) { if( ! result.hasErrors() ){ // note I haven't compiled this code :) } } }
我们的想法是在GET和POST上都会调用@modelattribute方法,在GET请求中它只会暴露给视图,而在POST上它将用于绑定请求参数.
请注意,BindingResult将传递给POST方法,以便您可以使用该命令执行某些操作.