SpringBoot集成 Thymeleaf,附Thymeleaf語(yǔ)法講解

SpringBoot中使用Thymeleaf

  1. pom依賴
        <!--thymeleaf視圖模板框架-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!--shiro模板視圖權(quán)限標(biāo)簽擴(kuò)展-->
        <dependency>
            <groupId>com.github.theborakompanioni</groupId>
            <artifactId>thymeleaf-extras-shiro</artifactId>
            <version>${thymeleaf-shiro.version}</version>
        </dependency>
  1. 配置項(xiàng)
spring:
  ## thymeleaf模板設(shè)置
  thymeleaf:
    prefix: classpath:/templates
    suffix: .html
    mode: HTML
    encoding: utf-8
    servlet.content-type: text/html
    cache: false
  1. 創(chuàng)建LoginController控制器,loginPage函數(shù)用來(lái)顯示登陸頁(yè)
@Controller
public class LoginController {

    @GetMapping("/login")
    public String loginPage(Model model) {
        ProjectProperties properties = SpringApplicationContextUtil.getBean(ProjectProperties.class);
        model.addAttribute("isCaptcha", properties.isCaptchaOpen());
        return "/login";
    }
}
  1. 創(chuàng)建templates模板目錄,并創(chuàng)建login.html登錄頁(yè)
    目錄結(jié)構(gòu)

    login.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="/common/template :: header(~{::title},~{::link},~{::style})">
    <title>EasyBoot登錄</title>
    <link rel="stylesheet" type="text/css" th:href="@{/css/login.css}">
</head>
<body class="layui-layout-login">
    <div class="login-bg">
        <div class="cover"></div>
    </div>
    <div class="login-content" th:th:classappend="${isCaptcha} ? 'captcha'">
        <h1 class="login-box-title"><i class="fa fa-fw fa-user"></i>登錄</h1>
        <form class="layui-form" th:action="@{/login}" method="post">
            <div class="layui-form-item">
                <label class="layui-icon layui-icon-username" for="username"></label>
                <input class="layui-input" type="text" name="username" id="username" placeholder="用戶名">
            </div>
            <div class="layui-form-item">
                <label class="layui-icon layui-icon-password" for="password"></label>
                <input class="layui-input" type="password" name="password" id="password" placeholder="密碼">
            </div>
            <div th:if="${isCaptcha}" class="layui-form-item captcha-item">
                <label class="layui-icon layui-icon-vercode"></label>
                <input class="layui-input" type="text" name="captcha" autocomplete="off" placeholder="驗(yàn)證碼">
                <img class="captcha-img" th:src="@{/captcha}" />
            </div>
            <div class="layui-form-item">
                <input type="checkbox" name="rememberMe" title="記住我" lay-skin="primary">
                <a class="layui-layout-right forget-password" href="javascript:alert('請(qǐng)聯(lián)系超級(jí)管理員!')">忘記密碼?</a>
            </div>
            <button type="submit" class="layui-btn layui-btn-fluid ajax-login"><i class="fa fa-sign-in fa-lg fa-fw"></i> 登錄</button>
        </form>
        <div class="layui-layer-loading login-page-loading"><div class="layui-layer-content"></div></div>
    </div>
<script th:replace="/common/template :: script"></script>
<script th:src="@{/js/login.js}" charset="utf-8"></script>
</body>
</html>

當(dāng)中用到了嵌入模板common/template.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:fragment="header(title, link, style)">
    <th:block th:if="${title == null}">
        <title>EasyBoot后臺(tái)</title>
    </th:block>
    <th:block th:if="${title != null}">
        <title th:replace="${title}">title</title>
    </th:block>
    <meta charset="utf-8">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

    <link rel="shortcut icon" th:href="@{/mo-favicon.ico}" type="image/x-icon">
    <link rel="stylesheet" th:href="@{/css/plugins/font-awesome-4.7.0/css/font-awesome.min.css}"  media="all">
    <link rel="stylesheet" th:href="@{/lib/layui-v2.3.0/css/layui.css}"  media="all">
    <link rel="stylesheet" th:href="@{/css/main.css}"  media="all">
    <th:block th:if="${link != null}">
        <th:block th:replace="${link}"></th:block>
    </th:block>

    <th:block th:if="${style != null}">
        <th:block th:replace="${style}"></th:block>
    </th:block>
</head>
<body>
    <th:block th:fragment="script">
        <script th:src="@{/lib/layui-v2.3.0/layui.js}" charset="utf-8"></script>
        <script th:src="@{/js/main.js}" charset="utf-8"></script>
    </th:block>
</body>
</html>

啟動(dòng)項(xiàng)目,顯示如下


頁(yè)面顯示

Thymeleaf語(yǔ)法

  1. th屬性
    常用th屬性解讀
    html有的屬性,Thymeleaf基本都有,而常用的屬性大概有七八個(gè)。其中th屬性執(zhí)行的優(yōu)先級(jí)從1~8,數(shù)字越低優(yōu)先級(jí)越高。
    ①th:text :設(shè)置當(dāng)前元素的文本內(nèi)容,相同功能的還有th:utext,兩者的區(qū)別在于前者不會(huì)轉(zhuǎn)義html標(biāo)簽,后者會(huì)。優(yōu)先級(jí)不高:order=7
    ②th:value:設(shè)置當(dāng)前元素的value值,類似修改指定屬性的還有th:src,th:href。優(yōu)先級(jí)不高:order=6
    ③th:each:遍歷循環(huán)元素,和th:text或th:value一起使用。注意該屬性修飾的標(biāo)簽位置,詳細(xì)往后看。優(yōu)先級(jí)很高:order=2
    ④th:if:條件判斷,類似的還有th:unless,th:switch,th:case。優(yōu)先級(jí)較高:order=3
    ⑤th:insert:代碼塊引入,類似的還有th:replace,th:include,三者的區(qū)別較大,若使用不恰當(dāng)會(huì)破壞html結(jié)構(gòu),常用于公共代碼塊提取的場(chǎng)景。優(yōu)先級(jí)最高:order=1
    ⑥th:fragment:定義代碼塊,方便被th:insert引用。優(yōu)先級(jí)最低:order=8
    ⑦th:object:聲明變量,一般和*{}一起配合使用,達(dá)到偷懶的效果。優(yōu)先級(jí)一般:order=4
    ⑧th:attr:修改任意屬性,實(shí)際開發(fā)中用的較少,因?yàn)橛胸S富的其他th屬性幫忙,類似的還有th:attrappend,th:attrprepend。優(yōu)先級(jí)一般:order=5
    常用th屬性使用
    使用Thymeleaf屬性需要注意點(diǎn)以下五點(diǎn):
    ①若要使用Thymeleaf語(yǔ)法,首先要聲明名稱空間: xmlns:th="http://www.thymeleaf.org"
    ②設(shè)置文本內(nèi)容 th:text,設(shè)置input的值 th:value,循環(huán)輸出 th:each,條件判斷 th:if,插入代碼塊 th:insert,定義代碼塊 th:fragment,聲明變量 th:object
    ③th:each 的用法需要格外注意,打個(gè)比方:如果你要循環(huán)一個(gè)div中的p標(biāo)簽,則th:each屬性必須放在p標(biāo)簽上。若你將th:each屬性放在div上,則循環(huán)的是將整個(gè)div。
    ④變量表達(dá)式中提供了很多的內(nèi)置方法,該內(nèi)置方法是用#開頭,請(qǐng)不要與#{}消息表達(dá)式弄混。
    ⑤th:insert,th:replace,th:include 三種插入代碼塊的效果相似,但區(qū)別很大。
    參考login.html
  2. 標(biāo)準(zhǔn)表達(dá)式語(yǔ)法
  • ~{...}:代碼塊表達(dá)式
  • {...}:消息表達(dá)式

  • @{...}:鏈接表達(dá)式
  • *{...}:選擇變量表達(dá)式
  • ${...}:變量表達(dá)式
    變量表達(dá)式使用頻率最高,其功能也是非常的豐富。所以我們先從簡(jiǎn)單的代碼塊表達(dá)式開始,然后是消息表達(dá)式,再是鏈接表達(dá)式,最后是變量表達(dá)式,隨帶介紹選擇變量表達(dá)式

~{...} 代碼塊表達(dá)式
支持兩種語(yǔ)法結(jié)構(gòu)
推薦:~{templatename::fragmentname}
支持:~{templatename::#id}
templatename:模版名,Thymeleaf會(huì)根據(jù)模版名解析完整路徑:/resources/templates/templatename.html,要注意文件的路徑。
fragmentname:片段名,Thymeleaf通過(guò)th:fragment聲明定義代碼塊,即:th:fragment="fragmentname"
id:HTML的id選擇器,使用時(shí)要在前面加上#號(hào),不支持class選擇器,支持標(biāo)簽選擇。
代碼塊表達(dá)式的使用
代碼塊表達(dá)式需要配合th屬性(th:insert,th:replace,th:include)一起使用。
th:insert:將代碼塊片段整個(gè)插入到使用了th:insert的HTML標(biāo)簽中,
th:replace:將代碼塊片段整個(gè)替換使用了th:replace的HTML標(biāo)簽中,
th:include:將代碼塊片段包含的內(nèi)容插入到使用了th:include的HTML標(biāo)簽中
參考login.html、template.html

<!-- template.html-->
<head th:fragment="header(title, link, style)">
...
</head>

<!-- login.html -->
<head th:replace="/common/template :: header(~{::title},~{::link},~{::style})">
...
</head>

#{...} 消息表達(dá)式
消息表達(dá)式一般用于國(guó)際化的場(chǎng)景。結(jié)構(gòu):th:text="#{msg}" 。
@{...} 鏈接表達(dá)式

  • 不管是靜態(tài)資源的引用,form表單的請(qǐng)求,凡是鏈接都可以用@{...} 。這樣可以動(dòng)態(tài)獲取項(xiàng)目路徑,即便項(xiàng)目名變了,依然可以正常訪問(wèn)
  • 鏈接表達(dá)式結(jié)構(gòu):
    無(wú)參:@{/xxx}
    有參:@{/xxx(k1=v1,k2=v2)} 對(duì)應(yīng)url結(jié)構(gòu):xxx?k1=v1&k2=v2
    引入本地資源:@{/項(xiàng)目本地的資源路徑}
    引入外部資源:@{/webjars/資源在jar包中的路徑}
<link th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="stylesheet">
<link th:href="@{/lib/layui-v2.3.0/css/layui.css}" rel="stylesheet">
<form class="form-login" th:action="@{/login}" th:method="post" >
<a class="btn btn-sm" th:href="@{/login.html(l='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/login.html(l='en_US')}">English</a>

${...}變量表達(dá)式
變量表達(dá)式有豐富的內(nèi)置方法,使其更強(qiáng)大,更方便。

  • 變量表達(dá)式功能
    ①可以獲取對(duì)象的屬性和方法
    ②可以使用ctx,vars,locale,request,response,session,servletContext內(nèi)置對(duì)象
    ③可以使用dates,numbers,strings,objects,arrays,lists,sets,maps等內(nèi)置方法(重點(diǎn)介紹)
  • 常用的內(nèi)置對(duì)象
    ①ctx :上下文對(duì)象。
    ②vars :上下文變量。
    ③locale:上下文的語(yǔ)言環(huán)境。
    ④request:(僅在web上下文)的 HttpServletRequest 對(duì)象。
    ⑤response:(僅在web上下文)的 HttpServletResponse 對(duì)象。
    ⑥session:(僅在web上下文)的 HttpSession 對(duì)象。
    ⑦servletContext:(僅在web上下文)的 ServletContext 對(duì)象
    這里以常用的Session舉例,用戶刊登成功后,會(huì)把用戶信息放在Session中,Thymeleaf通過(guò)內(nèi)置對(duì)象將值從session中獲取。
// java 代碼將用戶名放在session中
session.setAttribute("userinfo",username);
// Thymeleaf通過(guò)內(nèi)置對(duì)象直接獲取
th:text="${session.userinfo}"

常用的內(nèi)置方法
①strings:字符串格式化方法,常用的Java方法它都有。比如:equals,equalsIgnoreCase,length,trim,toUpperCase,toLowerCase,indexOf,substring,replace,startsWith,endsWith,contains,containsIgnoreCase等
②numbers:數(shù)值格式化方法,常用的方法有:formatDecimal等
③bools:布爾方法,常用的方法有:isTrue,isFalse等
④arrays:數(shù)組方法,常用的方法有:toArray,length,isEmpty,contains,containsAll等
⑤lists,sets:集合方法,常用的方法有:toList,size,isEmpty,contains,containsAll,sort等
⑥maps:對(duì)象方法,常用的方法有:size,isEmpty,containsKey,containsValue等
⑦dates:日期方法,常用的方法有:format,year,month,hour,createNow等

總結(jié)

1 . Thymeleaf 是Spring Boot 官方推薦的Java模版引擎框架,其文件擴(kuò)展名為.html

  1. Thymeleaf 幾乎支持所有的html屬性,用于賦值的th:text和th:value,用于循環(huán)遍歷的th:each,用于條件判斷的th:if
  2. Thymeleaf 提供四種標(biāo)準(zhǔn)的表達(dá)式,有豐富內(nèi)置方法的${},用于國(guó)際化的#{},用于代碼插入的~{},用于處理鏈接的@{}
  3. 一定要注意循環(huán)遍歷的th:each和代碼插入的th:insert用法,盡量避免破壞html結(jié)構(gòu)的細(xì)節(jié)問(wèn)題
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容