Java – basic spring MVC data binding
•
Java
I'm learning spring MVC. I'm looking for a basic controller to view data binding, but I haven't tried anything I can publish the view back to the controller, where I can see the POJO with attributes, but whenever I try to add the object to the model, I get nothing This is what I have done so far:
Regulator
@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); } }
The class I want to bind
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;} }
View – controller to form! work
<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>
What can I do or need to do to bind it?
Solution
Model properties are what you lack here
@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 :) } } }
Our idea is that @ modelattribute method will be called on both get and post. In get request, it will only be exposed to the view, while in post, it will be used to bind request parameters
Note that bindingresult is passed to the post method so that you can use the command to perform some operations
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码