对Session.getAttribute(),Request.setAttribute()和ModelMap.addAttribute()用法的理解

1.ModelMap对象主要用于传递控制方法处理数据到结果页面,也就是说咱们把结果页面上须要的数据放到ModelMap对象中便可,他的做用相似于request对象的setAttribute方法的做用,用来在一个请求过程当中传递处理的数据。经过如下方法向页面传递参数:  addAttribute(String key,Object value);  说白了就是ModelMap、Model、ModelAndView用于在控制器中放置数据到request中,以便转发给视图jsp好经过request.getAttribute取得。  spring

2.ModelMap的实例是由mvc框架自动建立并做为控制器方法参数传入,用户无需本身建立。ModelAndView的实例是由用户手动建立的,这也是和ModelMap的一个区别。  说白了就是ModelMap须要在参数中声明由springmvc传入,视图名经过return 返回,ModelAndView须要在方法体中本身new,new的同时构造函数参数要指定视图名。添加数据这两个用法是同样的。model和modelmap会自动转成modeladnview。  session

3.public String test1(@ModelAttribute("user") UserModel user)。如请求参数包含“?username=zhangsan&password=123456&workInfo.city=wh”自动绑定到user 中的workInfo属性的city属性中  说白了若是不加@ModelAttribute修饰参数,那么只是简单的自动将请求的数据按属性名绑定到user对象里,加了的话就能够在绑定参数数据的同时自动以user属性名添加到model里。更省事了。要否则还得手动写上 model.addAttribute("user",user); 固然还有可能先对user进行进一步的数据加工后再addAttribute("user") 。   mvc

4.session.setAttribute()和session.getAttribute()配对使用,做用域是整个会话期间,在全部的页面都使用这些数据的时候使用。request.setAttribute()和request.getAttribute()配对使用,做用域是请求和被请求页面之间。框架

5.@SessionAttributes  做用于Controller类,让Controller全部方法共享Model对象中一个或多个属性  再解释明白一点:就是原来model中有一个属性testId,如今在Controller上添加注解@SessionAttributes(“testId”),则全部方法均可以经过model获取该testId属性值。jsp

 

关于session,request,modelMap取值顺序:函数

Model model,HttpServletRequest request, ModelMap map声明变量 request.getSession().setAttribute("test", "haiwei2Session");对象

request.setAttribute("test", "haiwei1request");  ci

map.addAttribute("test", "haiweiModelMap");作用域

model.addAttribute("test", "haiweiModel");  get

我经过${test}这个方式取值,优先取Model和ModelMap的,Model和ModelMap是同一个东西,谁最后赋值的就取谁的,而后是request,最后是从session中获取。

相关文章
相关标签/搜索