SpringMVC 将数据传递到页面

1. BindingAwareModelMap(Model/ModelMap等等)传递数据

BindingAwareModelMap的继承关系如下

可以直接用BindingAwareModelMap作为请求参数,也可以用它的父类ModelMap / LinkedHashMap / Map等作为请求参数。SpringMVC会自动传入,实际类型就是BindingAwareModelMap。

从另一个继承树中也可得知,Model也可以作为请求参数。

1
2
3
4
5
6
7
8
9
/** Map<String, Object> map作为请求参数 */
@GetMapping("/test")
public String test(Map<String, Object> map) throws Exception {
System.out.println(map.getClass()); // BindingAwareModelMap
// map中的数据会放到请求域中
map.put("username", "jack");
map.put("intList", Arrays.asList(1, 2, 3));
return "index";
}
1
2
3
4
5
6
7
8
9
@GetMapping("/test")
public String test(ModelMap map) throws Exception {
System.out.println(map.getClass()); // BindingAwareModelMap
// 可以用put()或者addAttribute()
map.put("username", "jack");
map.put("intList", Arrays.asList(1, 2, 3));
map.addAttribute("msg", "你好");
return "index";
}
1
2
3
4
5
6
7
@GetMapping("/test")
public String test(Model model) throws Exception {
System.out.println(map.getClass()); // BindingAwareModelMap
model.addAttribute("username", "jack");
model.addAttribute("intList", Arrays.asList(1, 2, 3));
return "index";
}

可以看到无论用哪个参数,实际对象都是BindingAwareModelMap,最后值都会放入request域中

2. ModelAndView传递数据

ModelAndView

  • 包含视图信息(视图名)
  • 包含模型数据,传递给视图,数据也是放到request域中
1
2
3
4
5
6
7
8
9
10
@GetMapping("/test")
public ModelAndView test() {
// 构造方法的参数就是视图名,拼接得到/WEB-INF/jsp/index.jsp
ModelAndView mv = new ModelAndView("index");
// 设置数据
mv.addObject("username", "jack");
mv.addObject("intList", Arrays.asList(1, 2, 3));
// 返回mv
return mv;
}

创建ModelAndView时,也可以用空参构造,但是还要用setViewName()设置视图

1
2
3
4
5
6
7
8
@GetMapping("/test")
public ModelAndView test() {
ModelAndView mv = new ModelAndView();
mv.setViewName("index");
mv.addObject("username", "jack");
mv.addObject("intList", Arrays.asList(1, 2, 3));
return mv;
}

panchaoxin wechat
关注我的公众号
支持一下