JSP页面代码:
<form action="springmvc/ModelAttribute" method="POST">
<input type="hidden" name="id" value="1"/>
age:<input type="text" name="age" value="22"/><br><br>
username:<input type="text" name="username" value="Tom"/><br><br>
email:<input type="text" name="email" value="tom@163.com"/><br><br>
<input type="submit" value="Test ModelAttribute">
</form>
控制器层代码:
@Controller
@RequestMapping("/springmvc")
//@SessionAttributes(value={"user"},types=String.class)
public class SpringMVCTest02 {
private static final String SUCCESS ="success";
/**
* 18.测试@ModelAttribute注解
* @param user
* @return
*/
@RequestMapping(value="/ModelAttribute",method=RequestMethod.POST)
public String test18(UserBean user) {
System.out.println("模拟需要进行修改的user对象:"+user);
return SUCCESS;
}
@ModelAttribute
public void getUser(@RequestParam(value="id",required=false) Long id,
Map<String, Object> map) {
if (id != null) {
UserBean user = new UserBean();
user.setAge((short)21);
user.setId(new Long(1));
user.setUsername("Jerry");
user.setPassword("123456");
user.setEmail("jerry@163.com");
System.out.println("模拟从数据库获取的User对象:"+user);
map.put("user", user);
}
}
}
这是控制台输出:
模拟从数据库获取的User对象:UserBean [id=1, age=21, email=jerry@163.com, username=Jerry, password=123456, address=null]
模拟需要进行修改的user对象:UserBean [id=1, age=22, email=tom@163.com, username=Tom, password=null, address=null]
需求是把获取到password赋值给为null的password