Search code examples
javaspring-mvcmodelmodelandview

Difference between model and modelandview in spring


I have a method which is taking @modelattribute as the parameter and is returning model and view object as shown below

@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 loop is not printing anything whereas an object is added to model with name=demo.

in the view page which is result i am getting the value of modelattribute in requestScope.

Why the object demo is not added to model map? isnt the demo a model object?


Solution

  • Because, although the Employee object is added by the @ModelAttribute annotated parameter, you then create a brand new ModelAndView with the line

    ModelAndView m=new ModelAndView("result");
    

    Then you iterate over m which contains only a view name (i.e. "result") but no model.

    When you return a modelAndView, Spring will add to it all the other model attributes created by @ModelAttribute annotations.

    If you want to manilpulate the model in your method, add it as a parameter:

    @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));
         }
        }