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 /> 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM