一、历史回顾
(一)、springMVC的基本架构:
二、处理模型数据及ModelAttribute等注解的使用
(一)、处理模型数据
1、如果跳转时需要带数据:V、M,则可以使用以下方式:
ModelAndView、ModelMap、Map、Model ---数据放在了request
@SessionAttributes、@ModeAttribute。
2、部分底层代码分析:
ModelAndView.class的成员变量里面有关于视图的成员变量,可以通过构造方法的方式初始化。
例:
页面请求(index.jsp):
Controller控制请求:
响应请求(success.jsp):
例:下面是ModelMap、Map、Model
页面请求(index.jsp):
Controller控制请求:
响应请求(success.jsp):
3、如何将数据放入Session域
在类上加入注解@SessionAttributes。
@SessionAttributes(value="student1, student2")这样的注解可以放多个。
@SessionAttributes(types=Student.class)如果要在request中存放Student类型的对象,则同时将该类型对象也放到Session域。这里也可以放数组类型。例:@SessionAttributes(types={Student.class, Address.class})
例:
页面请求(index.jsp):
Controller控制请求:
响应请求(success.jsp):
(二)、@ModeAttribute注解
@ModeAttribute注解经常在更新的时候使用。通过@ModeAttribute修饰的方法,会在每次请求前先执行;并且该方法的参数map.put()可以将对象放入即将查询的参数中;必须满足约定:map.put(k, v)其中的k必须是即将查询的方法参数的首字母小写。public String modifyStudentById(Student xxx),即student。如果不一致,需要通过@ModeAttribute声明,即:map.put("stu", student) <---> @ModeAttribute("stu") Student student。
@ModeAttribute:
(1)、经常在更新时使用
(2)、在不改变原有代码的基础之上,插入一个新方法
@ModeAttribute在请求该类的各个方法之前,均被执行的。这个设计是基于一个思想:一个控制器只做一个功能。
根据Student类的对象的主键查询一个对象(从DB中查询或者其他),然后将其put到map中,这个put的的内容是map.put("student", student111),这里的key是student。这个将student首字母大写是执行方法参数的类型。然后将取出的值赋值给执行方法的对象中,然后执行前台对象的赋值。如下图所示:
例:
页面请求(index.jsp):
Controller控制请求:
注意如果queryStudentById方法中map的key和modifyStudentById方法参数的类型不一致的时候,需要匹配一下,如下图所示: