【问题标题】:Difference between model and modelandview in springspring中model和model和view的区别
【发布时间】:2015-03-27 18:47:15
【问题描述】:

我有一个方法,它以@modelattribute 作为参数并返回模型和视图对象,如下所示

@RequestMapping(value = "/pathtorequest", method = RequestMethod.POST)
    public ModelAndView redirectdemo( HttpServletRequest req,@ModelAttribute(value="demo") Employee e) {
        ModelAndView m=new ModelAndView("result");
        Map<String,Object> map=m.getModel();
        for(String s:map.keySet()){
            System.out.println("key::"+s+" value::"+map.get(s));
        }
        return m;
    }

foreach 循环不打印任何内容,而对象被添加到具有 name=demo 的模型中。

在视图页面中,我得到了 requestScope 中 modelattribute 的值。

为什么没有将对象演示添加到模型图中?演示不是模型对象吗?

【问题讨论】:

    标签: java spring-mvc model modelandview


    【解决方案1】:

    因为,虽然Employee对象是通过@ModelAttribute注解的参数添加的,但是你再用这行创建一个全新的ModelAndView

    ModelAndView m=new ModelAndView("result");
    

    然后你迭代 m ,它只包含一个视图名称(即“结果”)但没有模型。

    当你返回一个modelAndView时,Spring会将@ModelAttribute注解创建的所有其他模型属性添加到它。

    如果您想在方法中操作模型,请将其添加为参数:

    @RequestMapping(value = "/pathtorequest", method = RequestMethod.POST)
        public ModelAndView redirectdemo( HttpServletRequest req,@ModelAttribute(value="demo") Employee e, ModelMap modelMap) {
         for(String s : modelMap.keySet()){
            System.out.println("key::"+s+" value::"+modelMap.get(s));
         }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-13
      • 2012-11-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-05
      相关资源
      最近更新 更多