Thymeleaf對象的使用之基本對象實例解析
Thymeleaf中有許多內(nèi)置對象,可以在模板中實現(xiàn)各種功能。
下面有幾個基本對象。
Web對象常用有:request、session、servletContext。
Thymeleaf提供了幾個內(nèi)置變量param、session、application,分別可以訪問請求參數(shù)、session屬性、application屬性。
其中request的所有屬性可以直接使用 ${屬性名} 訪問。
備注:內(nèi)置對象與內(nèi)置變量是兩個概念,內(nèi)置對象使用“${#對象}”形式,內(nèi)置變量則不需要“#”。
開發(fā)環(huán)境:IntelliJ IDEA 2019.2.2
Spring Boot版本:2.1.8
新建一個名稱為demo的Spring Boot項目。
1、pom.xml加入Thymeleaf依賴:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
2、src/main/resources/templates/test1.html
<div th:text="${param.name1}"></div> <div th:text="${#request.getAttribute('name2')}"></div> <div th:text="${#session.getAttribute('name3')}"></div> <div th:text="${#servletContext.getAttribute('name4')}"></div> 上面也可以換成下面方式: <div th:text="${name2}"></div> <div th:text="${session.name3}"></div> <div th:text="${application.name4}"></div>
3、src/main/java/com/example/demo/Test1Controller.java
package com.example.demo; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import javax.servlet.http.HttpServletRequest; @Controller public class Test1Controller { @RequestMapping("/test1") public String test1(@RequestParam String name1, HttpServletRequest request){ request.setAttribute("name2", "b"); request.getSession().setAttribute("name3", "c"); request.getServletContext().setAttribute("name4","d"); return "test1"; } }
瀏覽器訪問:http://localhost:8080/test1?name1=a
頁面輸出:
a b c d 上面也可以換成下面方式: b c d
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- thymeleaf實現(xiàn)th:each雙重多重嵌套功能
- springboot+thymeleaf+druid+mybatis 多模塊實現(xiàn)用戶登錄功能
- Spring boot+mybatis+thymeleaf 實現(xiàn)登錄注冊增刪改查功能的示例代碼
- Spring boot2+jpa+thymeleaf實現(xiàn)增刪改查
- SpringBoot使用thymeleaf模板過程解析
- Spring Boot Thymeleaf實現(xiàn)國際化的方法詳解
- SpringBoot引入Thymeleaf的實現(xiàn)方法
- Thymeleaf中th:each及th:if使用方法解析
相關(guān)文章
Java針對ArrayList自定義排序的2種實現(xiàn)方法
這篇文章主要介紹了Java針對ArrayList自定義排序的2種實現(xiàn)方法,結(jié)合實例形式總結(jié)分析了Java操作ArrayList自定義排序的原理與相關(guān)實現(xiàn)技巧,需要的朋友可以參考下2018-01-01在Spring Boot中實現(xiàn)HTTP緩存的方法
緩存是HTTP協(xié)議的一個強大功能,但由于某些原因,它主要用于靜態(tài)資源,如圖像,CSS樣式表或JavaScript文件。本文重點給大家介紹在Spring Boot中實現(xiàn)HTTP緩存的方法,感興趣的朋友跟隨小編一起看看吧2018-10-10關(guān)于JDK15的新特性之TextBlocks文本塊的引入和使用
這篇文章主要介紹了關(guān)于JDK15的新特性之文本塊的引入和使用,如果具有一種語言學(xué)機制,可以比多行文字更直觀地表示字符串,而且可以跨越多行,而且不會出現(xiàn)轉(zhuǎn)義的視覺混亂,那么這將提高廣泛Java類程序的可讀性和可寫性,需要的朋友可以參考下2023-07-07javaweb中mysql數(shù)據(jù)庫連接步驟方法及其實例
這篇文章主要介紹了使用java web 連接MySQL數(shù)據(jù)庫的驅(qū)動方法的相關(guān)知識,本文介紹的非常詳細(xì),具有參考借鑒價值,需要的朋友可以參考下2017-04-04Springboot單體架構(gòu)http請求轉(zhuǎn)換https請求來支持微信小程序調(diào)用接口
這篇文章主要介紹了Springboot單體架構(gòu)http請求轉(zhuǎn)換https請求來支持微信小程序調(diào)用接口,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11