一、SpringMVC输出模型数据的几种常见途径
1、ModelAndView
@Controller
public class SpringmvcDemo {
@RequestMapping(value = "/testModelAndView", method = RequestMethod.GET)
public ModelAndView testSpringMVC() {
// 使用ModelAndView的方式
ModelAndView mav = new ModelAndView();
mav.addObject("username", "damaomao");
mav.setViewName("testModelAndView");
System.out.println("测试ModelAndView");
return mav;
}
}
2、Map<Object,Object>集合
@Controller
public class SpringmvcDemo {
@RequestMapping(value = "/testModelAndView", method = RequestMethod.GET)
// 使用返回值是String类型,参数为map
public String testSpringMVC01(Map<String,Object> map) {
map.put("user01","xiaomao");
map.put("user02","xiaomaomao");
map.put("user03","xiaoxiaomaomao");
return "testModelAndView";
}
}
3、Model对象
@Controller
public class SpringmvcDemo {
@RequestMapping(value = "/testModelAndView", method = RequestMethod.GET)
// 使用返回值是String类型,参数为map
public String testSpringMVC01(Model model) {
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("user01","haha");
hashMap.put("user02","hehe");
hashMap.put("user03","heihei");
model.addAllAttributes(hashMap);
return "testModelAndView";
}
}
二、ModelAndView源码参考
通过上面源码看出使用上述几种输出模型本质上都是Servlet中的request.getDispatcher.forward(request,response)的方式往域对象中存储值.
原文:https://www.cnblogs.com/xiaomaomao/p/13599535.html