
正文
SpringBoot入门06-Thymeleaf显示作用域对象种的对象
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
作用域对象request,session, servletContext中的数据在Thymeleaf中的显示都是相同的
作用域对象中的 List和Set的集合在html中的显示是相同的
作用域对象中的显示字符串或基本类型是相同的
springboot中怎样使用session?
方式一,使用注解@SessionAttributes确定键,然后用ModerAndView对象添加对应的值后返回页面
方式二 处理方法中使用参数HttpSession
springboot怎样获取ServletContext
方法一 request获取servletContext
ServletContext servletContext = request.getServletContext();
方法二 使用ContextLoader
ServletContext servletContext = ContextLoader.getCurrentWebApplicationContext().getServletContext();
方法三 使用spring注入自动注入
@Autowired private ServletContext servletContext;
在Thymeleaf中显示作用域对象字符串或基本类型
将要显示的对象设置在标签内部,就算标签内部有内容也会被替换掉, 也可以使用不存在的标签替换
设置方式:${name}
设置为标签属性的值,要在属性前面加上 "th:"
1 modelAndView.addObject("i", 100);
2 -----------------------------------------------------------------
3 <span th:text="${i}"></span>
4 <div th:text="${i}"></div>
5 <h1 th:text="${i}"></h1>
6 <wgr style="color: red;" th:text="${i}"></wgr>
7 <span style="color: red;" th:text="${i}"></span>
8 <div style="color: red;" th:text="${i}"></div>
9 <h1 style="color: red;" th:text="${i}"></h1>
10 <wgr style="color: red;" th:text="${i}"></wgr> <br />
11 <input type="text" th:value="${i}" />
12 <input type="submit" th:value="${i}"/>
13 <input type="text" th:id="${i}" />
对象
1 modelAndView.addObject("stu", new Stu(1, "小明", 12));
2
3 ---------------------------------------------------------
4
5 <span th:text="${stu.id}"> </span>
6
7 <span th:text="${stu.name}"> </span>
8
9 <span th:text="${stu.age}"> </span>
集合遍历
1 List<String> strList = new ArrayList<>();
2 strList.add("小明");
3 strList.add("小华");
4 strList.add("小陶");
5 modelAndView.addObject("strList", strList);
6 ---------------------------------------------------------
7 <div th:each="str:${strList}"> //div可以改为任意的容器标签,甚至是不存在的标签
8 <span style="color: red;" th:text="${str}"></span> <br />
9 </div>
显示session和ServletContext中数据
默认显示request中数据,
显示session中数据要加上 session前缀
显示servletContext中数据要加上application前缀
1 //装到request
2 request.setAttribute("requestAge", 100);
3 //装到session
4 session.setAttribute("sessionName", "小明");
5 //装到ServletContext
6 servletContext.setAttribute("applicationNum", 1);
7 --------------------------------------------------------------------------------------
8 request中:
9 <span style="color: red;" th:text="${requestAge}"></span><br />
10 session中:
11 <span style="color: red;" th:text="${session.sessionName}"></span><br />
12 servletContext中:
13 <span style="color: red;" th:text="${application.applicationNum}"></span><br />






