[JAVAEE] Thymeleaf 基本语法:常用表达式
Thymeleaf 基本語法
常用表達式
- 變量表達式 ${ }
- 使用方法:th:xx = “${ }” 獲取對象屬性值給 th:xx 。
- 后臺代碼:
Student s=new Student(2019001,"小明");
model.addAttribute("stu",s);
- 前端代碼:
${stu.***} 獲得stu對象屬性值
th:text:文本標簽,用于進行文本替換
<p th:text="${stu.id}"></p>
<p th:text="${stu.name}"></p>
補充:th:text 和 th:utext
- th:text 不會解析html(稱為被HTML轉(zhuǎn)義)
- th:utext 會解析html(稱為不執(zhí)行HTML轉(zhuǎn)義)
- 后臺代碼:
model.addAttribute("msg","<h1>hello</h1>");
- 前端代碼:
<p th:text = "${msg}" >hello</p>
<p th:utext = "${msg}" >hello</p>
- 運行結(jié)果:
${ } 一些用法示例
字符串連接、數(shù)學(xué)運算、布爾邏輯和三目運算等。
- 字符串連接:
<p th:text=" '歡迎' + ${stu.name} ">hello</p> - 錯誤用法:
<p th:text=" 歡迎 ${stu.name} ">hello</p> - | | 和 + 效果一樣
<p th:text=" |歡迎 ${stu.name}| ">hello</p> - 三目運算
<p th:text=" '歡迎' + ${ stu.name!=null ? stu.name : 'nobody' } ">hello</p> - 算數(shù)運算
<p th:text="1+3">結(jié)果1</p>
<p th:text="9%2">結(jié)果2</p>
補充:三目運算
- If-then-else:
(if) ? (then) : (else) - If-then:
(if) ? (then) - Default:
(value) ? : (defaultvalue)
- 選擇(星號)表達式 *{ }
- 使用方法:首先通過 th:object 獲取對象,然后使用 th:xx = “*{ }” 獲取對 象屬性值(*表示不用寫對象名)。
- 后臺代碼:
Student s=new Student(2019001,"小明");
model.addAttribute("stu",s);
- 前端代碼:
<div th:object="${stu}"><p th:text="*{id}"></p><p th:text="*{name}"></p>
</div>
- 運行結(jié)果
- 消息(#)表達式 #{ }
- 主要是用于讀取自定義屬性文件(.properties)中的值,常用于國際化。
(1)在 templates 目錄中新建屬性文件 message.properties,并寫入以下內(nèi)容:
home.province=Hubei
home.city=Wuhan
(2)在 application.properties 中加入屬性文件所在位置:
#指定屬性文件所在位置
spring.messages.basename=templates/message
(3)頁面中讀取配置文件:
<p th:text="#{home.province}"></p>
<p th:text="#{home.city}"></p>
- 運行結(jié)果:
- 鏈接表達式 @{ }
- 使用方法:通過鏈接表達式
@{ }直接拿到應(yīng)用路徑,然后拼接靜態(tài)資源路徑。
th:src 用于設(shè)置圖片來源
th:attr 用于設(shè)置屬性
HTML原生寫法:<img src="/images/蘇軾.jpg">
注:先將圖片資源放在 static 的 images 目錄中
<img th:src="@{/images/蘇軾.jpg}"/>
另一種寫法:
<img th:attr="src=@{/images/蘇軾.jpg}" />
補充:如果圖片沒有顯示,需要 build 菜單 → rebuild項目
-
th:href 用于設(shè)置超鏈接值(http://localhost:8080/)
<a th:href="@{/}">首頁</a> -
生成的url:http://localhost:8080/test1?id=2019001&name=小明
<a th:href="@{/test1(id=${stu.id}, name=${stu.name})}">跳轉(zhuǎn)</a> -
( 變量名=值,變量名=值 ) 括起作為url參數(shù)
-
生成的url:http://localhost:8080/test5/2019001/小明
-
稱為:RESTful 風格請求
<a th:href="@{/test5/{id}/{name}(id=${stu.id},name=${stu.name})}">跳轉(zhuǎn)</a>
- 片段表達式 ~{ }
- 一般和模版布局語法一起使用
總結(jié)
以上是生活随笔為你收集整理的[JAVAEE] Thymeleaf 基本语法:常用表达式的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 黄色激光的波长一般在多少纳米?
- 下一篇: 新买的车办理车辆临时牌照需要多久?