zoukankan      html  css  js  c++  java
  • SpringMVC的Model ModeMap ModelAndView @ModelAttribute @SessionAttribute区分

    Spring MVC整理系列(05)————Spring MVC配置解析及整合SpriSpring MVC之@ModelAttribute、@SessionAttributes以及Model的使用介绍

    http://blog.csdn.net/javaloveiphone/article/details/51802367

    Spring MVC如何向视图传值--Model--ModelMap--ModelAndView--@ModelAttribute

    https://www.cnblogs.com/sonng/archive/2017/03/30/6648917.html

     ModelMap、ModelAndView和@Modelattribute的区别

    http://blog.csdn.net/tomcat_2014/article/details/48241037

     ModelMap

    http://a-bun.iteye.com/blog/1176276

    ModelMap vs Model in Spring MVC

    https://stackoverflow.com/questions/28195677/modelmap-vs-model-in-spring-mvc

    总结:

    1.ModelMap对象主要用于传递控制方法处理数据到结果页面,也就是说我们把结果页面上需要的数据放到ModelMap对象中即可,他的作用类似于request对象的setAttribute方法的作用,用来在一个请求过程中传递处理的数据。通过以下方法向页面传递参数: 
    addAttribute(String key,Object value);

    说白了就是ModelMap、Model、ModelAndView用于在控制器中放置数据到request中,以便转发给视图jsp好通过request.getAttribute取得。

    2.ModelMap的实例是由mvc框架自动创建并作为控制器方法参数传入,用户无需自己创建。ModelAndView的实例是由用户手动创建的,这也是和ModelMap的一个区别。

    说白了就是ModelMap需要在参数中声明由springmvc传入,视图名通过return 返回,ModelAndView需要在方法体中自己new,new的同时构造函数参数要指定视图名。添加数据这两个用法是一样的。model和modelmap会自动转成modeladnview。

    3.public String test1(@ModelAttribute("user") UserModel user)。如请求参数包含“?username=zhang&password=123&workInfo.city=bj”自动绑定到user 中的workInfo属性的city属性中

    说白了如果不加@ModelAttribute修饰参数,那么只是简单的自动将请求的数据按属性名绑定到user对象里,加了的话就可以在绑定参数数据的同时自动以user属性名添加到model里。更省事了。要不然还得手动写上 model.addAttribute("user",user); 当然还有可能先对user进行进一步的数据加工后再addAttribute("user")

    4. @ModelAttribute还有两个高级应用,参考http://blog.csdn.net/tomcat_2014/article/details/48241037 吧

    1. @ModelAttribute("hb")  
    2. public List<String> hobbiesList(){  
    3.     List<String> hobbise = new LinkedList<String>();  
    4.     hobbise.add("basketball");  
    5.     hobbise.add("football");  
    6.     hobbise.add("tennis");  
    7.     return hobbise;  

    public @ModelAttribute("user2") UserModel test3(@ModelAttribute("user2") UserModel user)

    5.@SessionAttributes

    作用于Controller类,让Controller所有方法共享Model对象中一个或多个属性
    再解释明白一点:就是原来model中有一个属性testId,现在在Controller上添加注解@SessionAttributes(“testId”),则所有方法都可以通过model获取该testId属性值

    SessionStatus.setComplete()用于清除session
  • 相关阅读:
    docker 基础
    shell
    MySQL之MGR
    MySQL之读写分离
    MySQL主从复制
    MySQL之数据类型
    MySQL之索引与约束条件
    SQL语句进阶
    SQL语句初识
    Linux之MySQL安装
  • 原文地址:https://www.cnblogs.com/coolzdp/p/7989873.html
Copyright © 2011-2022 走看看