Spring MVC3: Controller接受Form数据
<form action="./saveIntoDatabase.do" method="post" name="saveIntoDatabase">
<input name="name" type="text">
<input name="password" type="text">
<input type="submit" value="Submit">
</form><br>
<form action="./saveObject.do" method="post" name="saveObject">
<input name="name" type="text">
<input name="password" type="text">
<input type="submit" value="Submit">
</form><br>
Controller:
@RequestMapping(value="/saveIntoDatabase.do")
public ModelAndView saveIntoDB(@RequestParam("name")String name,@RequestParam("password")String password){
ModelAndView view = new ModelAndView("helloWord");
view.addObject("message", "saveIntoDB. name="+name);
return view;
}
//A
@RequestMapping(value="/saveObject.do", method=RequestMethod.POST)
public ModelAndView saveObject(@ModelAttribute("user")User user){
ModelAndView view = new ModelAndView("helloWord");
view.addObject("message", "saveObject. name1="+user.getName());
return view;
}
//B
@RequestMapping(value="/saveObject.do", method=RequestMethod.POST)
public ModelAndView saveObject(@ModelAttribute("user1")User user2){
ModelAndView view = new ModelAndView("helloWord");
view.addObject("message", "saveObject. name1="+user2.getName());
return view;
}
//C
@RequestMapping(value="/saveObject.do", method=RequestMethod.POST)
public ModelAndView saveObject(@ModelAttribute User user){
ModelAndView view = new ModelAndView("helloWord");
view.addObject("message", "saveObject. name1="+user.getName());
return view;
}
public String doCreate(@Valid @ModelAttribute("appForm") CreateAppForm appForm,
BindingResult result, ...) {
...
}
参考:
@RequestParam:只针对单个参数。
@ModelAttribute:适用于对象赋值。@ModelAttribute("user1")里面的字符串好像没什么要求?user2就是一个pojo,属性跟form里面控件的name对应。
A,B,C处都不会影响user的属性值,搞不明白,知道的可以告诉我,谢谢。
@ModelAttribute 声明在属性上,表示该属性的value 来源于model 里"queryBean" ,并被保存到model 里@ModelAttribute 声明在方法上,表示该方法的返回值被保存到model里。
其中的@ModelAttribute和BindingResult 中间不能有其它参数,否则会出现如下错误:
Errors/BindingResult argument declared without preceding model attribute. Check your handler method signature!