7.1 使用场景

image.png
image.png

7.2 示例代码

在方法定义上使用 @ModelAttribute 注解:Spring MVC 在调用目标处理方法前,会先逐个调用在方法级上标注了 @ModelAttribute 的方法。

在方法的入参前使用 @ModelAttribute 注解:可以从隐含对象中获取隐含的模型数据中获取对象,再将请求参数绑定到对象中,再传入入参

将方法入参对象添加到模型中


①页面表单

  1. <!--测试 @ModelAttribute 类似Struts2框架的模型驱动 -->
  2. <!--
  3. 模拟修改操作:
  4. 1.原始数据为:1,Tom,123456,tom@atguigu.com,12
  5. 2.密码不需要修改
  6. 3.表单回显,模拟操作直接在表单value属性上赋值
  7. -->
  8. <form action="springmvc/testModelAttribute" method="POST">
  9. <input type="hidden" name="id" value="1"><br>
  10. username: <input type="text" name="username" value="Tom"/><br>
  11. email: <input type="text" name="email" value="tom@atguigu.com"/><br>
  12. age: <input type="text" name="age" value="12"/><br>
  13. <input type="submit" value="Submit"/>
  14. </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);
    }
}

image.png如果不在参数上使用@ModelAttribute就直接用变量名查找

    @RequestMapping("/MV")
    public String MAT(@ModelAttribute("book")Book book) {
        System.out.println("更新后的图书:" + book);
        return "success";
    }

    @ModelAttribute
    public String priM(Map<String , Book>map) {
        Book book = new Book("11", "22", 33.0, 44, 55);
        System.out.println("更新前的图书:" + book);
        map.put("book", book);
        return "";
    }
@RequestMapping("/testModelAttribute")
//public String testModelAttribute(User user){

    public String testModelAttribute(@ModelAttribute("abc") User user){

    System.out.println("修改 user="+user);                
    return "success";
    }

/**
 * @ModelAttribute 注解也可以来修饰目标方法 POJO 类型的入参, 其 value 属性值有如下的作用:
1). SpringMVC 会使用 value 属性值在 implicitModel 中查找对应的对象, 若存在则会直接传入到目标方法的入参中.
2). SpringMVC 会以 value 为 key, POJO 类型的对象为 value, 存入到 request 中. 
 */
@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); //BindingAwareModelMap

    //map.put("abc", user); //BindingAwareModelMap
    }
}

7.3 @ModelAttribute源码参考

@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ModelAttribute {
/**
 * The name of the model attribute to bind to.
 * <p>The default model attribute name is inferred from the declared
 * attribute type (i.e. the method parameter type or method return type),
 * based on the non-qualified class name:
 * e.g. "orderAddress" for class "mypackage.OrderAddress",
 * or "orderAddressList" for "List&lt;mypackage.OrderAddress&gt;".
 */
String value() default ""; 
}

7.4 @ModelAttribute注解之运行原理★

image.png
运行原理:
① 执行@ModelAttribute注解所修饰的方法,将从数据库中获取的对象存放到Map集合中,key为user

② SpringMVC从Map集合中获取 user对象,将表单数据封装到与参数名称对应的user对象属性上

③ SpringMVC将user对象作为参数,传递给目标方法。

④ 注意:@ModelAttribute 注解修饰的方法中,放入到Map集合中的key值,应该和目标方法参数类型的类名称首字母小写一致。

7.5 @sessionAttributes注解引发的异常

①由@SessionAttributes引发的异常
image.png②如果在处理类定义处标注了@SessionAttributes(“xxx”),则尝试从会话中获取该属性,并将其赋给该入参,然后再用请求消息填充该入参对象。如果在会话中找不到对应的属性,则抛出 HttpSessionRequiredException 异常
image.png