SpringMvc Model与ModelAndView

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_43014205/article/details/85338981

在springmvc中,有两种方式将数据由服务器发送到jsp

1.ModelAndView

  @RequestMapping("/testModelandView")
    public ModelAndView testModel(){
        ModelAndView modelAndView = new ModelAndView();
        //将数据存在了request域中
        modelAndView.addObject("name","DELL");
        modelAndView.setViewName("/result.jsp");
        return modelAndView;
    }

2.model(相当于一个map)

model的实例是springmvc框架自动创建并作为控制器方法参数传入,用户无需自己创建



    @RequestMapping("/testModel")
    public String testmodel2(Model model){
        //将数据存在了request域中
        model.addAttribute("name","lenovo");
        return "/result.jsp";
    }

两种方法都是将数据存在了request域中      在jsp中可以使用el表达式进行取值

Model中的方法

1.addAttribute(String attributeName,Object attributeValue);添加键值属性对

2.asMap();     将当前的model转成map

 model.addAttribute("name","lenovo");
        System.out.println(model.asMap());
/*
*{name=lenovo}
*/

3.addAttribute(Object  o);将一个对象存在model当中

既然把对象存在了model中,说model相当于一个map,也就是把对象放在了map里面,map是有key、value的,value是这个对象,那么key是什么?这个对象所在的类的类名,且把类名的第一个字母小写作为其key值

@RequestMapping("/testModel")
    public String testmodel2(Model model){
        //将数据存在了request域中
        Goods mygoods = new Goods();
        mygoods.setName("笔记本");
        mygoods.setPrice(20);
        model.addAttribute(mygoods);
        System.out.println(model.asMap());
        return "/result.jsp";
    }
/*
*{goods=Goods{name='笔记本', price=20}}
*/

4.addAllAttribute(Map<String,?> hashmap);向model中添加一个map

将map中的内容复制到当前的model中,如果当前的model中含有相同的key值,则前者会被后者覆盖

  @RequestMapping("/testModel")
    public String testmodel2(Model model){
        //将数据存在了request域中
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("name","dell");
        hashMap.put("price",20);
        hashMap.put("name","lenovo");
        model.addAllAttributes(hashMap);
        System.out.println(model.asMap());
        return "/result.jsp";
    }
/
*{price=20, name=lenovo}
*/

5.addAllAttribute(Collection list);向model中添加一个集合

以集合当中的类型作为key,将所提供的Collection中的属性复制到model中,有相同类型,则会覆盖

 @RequestMapping("/testModel")
    public String testmodel2(Model model){
        //将数据存在了request域中
        ArrayList<Object> list = new ArrayList<>();
        list.add("name");
        list.add(10);
        list.add("goods");
        model.addAllAttributes(list);
        System.out.println(model.asMap());
        return "/result.jsp";
    }
/
*{string=goods, integer=10}
*/

6.mergeAttribute(Map <String,?>  hashmap)

同addAllAttribute相同,不过是有key值相同的不会覆盖以前的

7.containsAttribute(String  name)

判断model中是否包含一个键值对    返回布尔类型

猜你喜欢

转载自blog.csdn.net/weixin_43014205/article/details/85338981