春季模特与模范观的区别

时间:2015-03-27 18:47:15

标签: java spring-mvc model modelandview

我有一个方法,它将@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循环不打印任何内容,而对象被添加到名称= demo的模型中。

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

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

1 个答案:

答案 0 :(得分:1)

因为尽管通过@ModelAttribute注释参数添加了Employee对象,但是然后使用行创建一个全新的ModelAndView

ModelAndView m=new ModelAndView("result");

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

当您返回一个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));
     }
    }