@ModelAttribute注解
1 @ModelAttribute注解之使用场景【了解】
2@ModelAttribute注解之示例代码
- 在方法定义上使用 @ModelAttribute 注解:Spring MVC 在调用目标处理方法前,会先逐个调用在方法级上标注了 @ModelAttribute 的方法。
- 在方法的入参前使用 @ModelAttribute 注解:可以从隐含对象中获取隐含的模型数据中获取对象,再将请求参数绑定到对象中,再传入入参
- 将方法入参对象添加到模型中
- 示例代码
- 页面表单
<!–测试 @ModelAttribute 类似Struts2框架的模型驱动 –> <!– 模拟修改操作: 1.原始数据为:1,Tom,123456,tom@atguigu.com,12 2.密码不需要修改 3.表单回显,模拟操作直接在表单value属性上赋值 –> <form action=”springmvc/testModelAttribute” method=”POST”> <input type=”hidden” name=”id” value=”1″><br> username: <input type=”text” name=”username” value=”Tom”/><br> email: <input type=”text” name=”email” value=”tom@atguigu.com”/><br> age: <input type=”text” name=”age” value=”12″/><br> <input type=”submit” value=”Submit”/> </form> |
- 增加@ModelAttribute注解
//1. 由 @ModelAttribute 标记的方法, 会在每个目标方法执行之前被 SpringMVC 调用! @RequestMapping(“/testModelAttribute”) public String testModelAttribute(User user){ System.out.println(“user=”+user); return “success”; } @ModelAttribute public void getUser(@RequestParam(value=”id”,required=false) Integer id,Map<String,Object> map){ if(id!=null){ //模拟从数据库中获取到的user对象 User user = new User(1,”Tom”,”123456″,”tom@atguigu.com”,12); System.out.println(“从数据库中查询的对象:user=”+user ); map.put(“user”, user); } } |
- 测试
- 异常
//org.springframework.web.HttpSessionRequiredException: Session attribute ‘user’ required – not found in session
//出现这个异常,是@SessionAttributes(value={“user”},types={String.class})导致的,去掉类上的这个注解
想要了解跟多关于java培训课程内容欢迎关注尚硅谷java培训,尚硅谷除了这些技术文章外还有免费的高质量java培训课程视频供广大学员下载学习。