1、使用ServletAPI向request域对象共享数据
①控制器
@Controller
public class HelloController {@RequestMapping("/test")public String index(HttpServletRequest request){request.setAttribute("test","test666");return "index";}
}
②index页面读取域
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
success
<p th:text="${test}"></p>
</body>
</html>
③效果
2. 使用ModelAndView向request域对象共享数据(建议使用)
必须把该方法的返回值返回
* ModelAndView有Model和View的功能
* Model主要用于向请求域共享数据
* View主要用于设置视图,实现页面跳转
①控制器
@Controller
public class HelloController {@RequestMapping("/test")public ModelAndView index(){ModelAndView mav = new ModelAndView();mav.addObject("test","test777");//保存请求域的值mav.setViewName("index");//跳转页面return mav;}
}
②主页
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
success
<p th:text="${test}"></p>
</body>
</html>
③测试
3. 使用Model向request域对象共享数据
@Controller
public class HelloController {@RequestMapping("/")public String index(Model model){model.addAttribute("test","test888");return "index";}
}
4.使用map向request域对象共享数据
@Controller
public class HelloController {@RequestMapping("/")public String index(Map<String,Object> map){map.put("test","test999");return "index";}
}
5. 使用ModelMap向request域对象共享数据
@Controller
public class HelloController {@RequestMapping("/")public String index(ModelMap modelMap){modelMap.addAttribute("test","test999");return "index";}
}
6.Model、ModelMap和Map的关系
Model、ModelMap、Map类型的参数其实本质上都是 BindingAwareModelMap类型的
在html获取请求域的值是th:text=”${名}”,获取session的值是th:text=”${session.名}”,获取application域对象的值是th:text=”${application.名}”
7.向session域共享数据
①前端控制器
@RequestMapping("/")
public String index(HttpSession session){session.setAttribute("test","test111");return "index";
}
②静态html页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
success
<p th:text="${session.test}"></p>
</body>
</html>
8.向application域共享数据
①前端控制器
@RequestMapping("/")
public String index(HttpSession session){ServletContext application = session.getServletContext();application.setAttribute("test","test222");return "index";
}
②html页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
success
<p th:text="${application.test}"></p>
</body>
</html>
【关系】
①request (HttpservletRequest类) 一次请求有效
②session (HttpSession类) 一个会话有效(打开游览器,关闭浏览器)
③application(ServletContext类) 整个web工程范围有效