注:这里的使用了thymeleaf视图解析器
使用原生的servletAPI向request域对象共享数据(不建议使用)
<p th:text="${这里写控制器中,其控制方法的形参(HttpServletRequest request),
在函数体中调用的setAttribute()方法中设置的键名}"></p>
--然后在网页中就会对应的位置出现在setAttribute()方法中设置的对应的值
--自己测试了一下,这个方法只有return回来的那个页面中有用,只在同一个函数体范围生效,在其他的控制器方法中,对应的页面无效
使用ModeAndView向request域对象共享数据
用这种方式的控制器方法,返回值必须是ModeAndView类型的
- 控制器方法返回值是ModeAndView类型
- 要创建ModeAndView类型的对象
- 要对ModeAndView对象设置模型数据-->向request域对象中共享数据
- 设置视图名称-->这样视图解析器才能处理
使用Model向request域对象共享数据
需要在控制方法中设置Model类型的形参,然后调用形参的addAttribute()方法
使用Map向request域对象共享数据
形参-->Map<String,Object> map --一般的键都是String类型,而值的类型根据具体情况而定
共享数据-->mao.put("键","值")
使用ModelMap向 request域对象共享数据
用法和 第三个Model类似,不赘述
使用原生servletAPI向session域共享数据
//控制器中的控制方法
@RequestMapping("/testSession")
public String testSession(HttpSession session){
session.setAttribute("testSessionScope","hello,session");
return "success";
}
在页面中调用数据与request有所不同
<p th:text="${testRequestScope}"></p>
<p th:text="${session.testSessionScope}"></p>
前者request,后者session
向application域共享数据
@RequestMapping("/testApplication")
public String testApplication(HttpSession session){
ServletContext application = session.getServletContext();
application.setAttribute("testApplicationScope","hello,Application");
return "success";
}
<p th:text="${application.testApplicationScope}"></p>
总结:向request域对象中共享数据的方法,除了第二种,其余方法都比较类似