在springmvc中的ModelAndView和Model有什么区别呢?其实它们只是表现形式不太一样,两者基本上是可以相互替代的,下面用两个小案例来解释springmvc中的ModelAndView和Model之间的区别。
比如我们跳转到一个web界面,并且需要传递参数,该怎么做呢?先用Model来实现传值,代码如下:
@GetMapping("/question") public String index(Model model) { List<QuestionType> questionTypes = questionTypeMapper.selectAll(); model.addAttribute("questionTypes", questionTypes); return "admin/question/question"; }
上面用的是Model对象,跳转界面直接return就可以了,参数则是通过model.addAttribute(key,value)来传递到下一页。
那么使用ModelAndView对象该怎么实现同样的功能呢?其实很简单,代码如下:
@GetMapping("/question") public String index() { List<QuestionType> questionTypes = questionTypeMapper.selectAll(); return new ModelAndView("admin/question/question","questionTypes",questionTypes); }
上面ModelAndView构造函数的三个参数分别是new ModelAndView(viewName,key,value);
两者使用很简单,随便可以都可以用。