方式一:通过Model
后端代码:
@GetMapping("/test")
public String hello(@RequestParam(value = "type",required = false) String type, Model model){
//封装要显示到视图中的数据
model.addAttribute("msg","吾等为何而战");
return "test";
}
方式二:通过ModelAndView
@GetMapping("/hello")
public ModelAndView getIndex(@RequestParam(value = "type",required = false) String type){
//返回一个模型视图对象
ModelAndView mv = new ModelAndView();
mv.addObject("msg",type);
mv.setViewName("index");//返回页面为index
return mv;
}
方式三:通过通过ModelMap
@GetMapping("/hello")
public String hello(@RequestParam("username") String name, ModelMap model){
//封装要显示到视图中的数据
//相当于req.setAttribute("name",name);
model.addAttribute("name",name);
System.out.println(name);
return "hello";
}
方式四:使用map传递
@GetMapping("/hello")
public String hello(@RequestParam("username") String name, Map<String,Object> map){
//封装要显示到视图中的数据
map.put("name",name);
System.out.println(name);
return "hello";
}
三种方式前端取值代码类似,下面是方式一对应的前端代码
前端代码:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>test</title>
<script src="../static/js/jquery-1.4.4.min.js"></script>
</head>
<body>
<script th:inline="javascript">
$(function () {
var tt=[[${msg}]];//取值
console.info(tt);
})
</script>
<h1>testttt</h1>
</body>
</html>
前端结果::
三者的区别
Model 只有寥寥几个方法只适合用于储存数据,简化了新手对于Model对象的操作和理解;
ModelMap 继承了 LinkedMap ,除了实现了自身的一些方法,同样的继承 LinkedMap 的方法和特性;
ModelAndView 可以在储存数据的同时,可以进行设置返回的逻辑视图,进行控制展示层的跳转。
参考:SpringMVC将数据显示到前端的三种方式
Springboot+Thymeleaf通过JS获取Model传过来的对象的值,存储到Session中