Spring Boot(四):Spring Boot 集成 Thymeleaf

Thymeleaf是一款用于渲染XML/XHTML/HTML5內(nèi)容的模板引擎。類似JSP,Velocity,F(xiàn)reeMaker等,它也可以輕易的與Spring MVC等Web框架進(jìn)行集成作為Web應(yīng)用的模板引擎。與其它模板引擎相比,Thymeleaf最大的特點(diǎn)是能夠直接在瀏覽器中打開(kāi)并正確顯示模板頁(yè)面,而不需要啟動(dòng)整個(gè)Web應(yīng)用,這是由于它支持 html 原型,然后在html 標(biāo)簽里增加額外的屬性來(lái)達(dá)到模板+數(shù)據(jù)的展示方式。瀏覽器解釋html 時(shí)會(huì)忽略未定義的標(biāo)簽屬性,所以thymeleaf 的模板可以靜態(tài)地運(yùn)行;當(dāng)有數(shù)據(jù)返回到頁(yè)面時(shí),Thymeleaf 標(biāo)簽會(huì)動(dòng)態(tài)地替換掉靜態(tài)內(nèi)容,使頁(yè)面動(dòng)態(tài)顯示。---摘自百度君。

要寫(xiě)出簡(jiǎn)潔優(yōu)雅的前臺(tái)代碼,Spring Boot 君推薦使用Thymeleaf替代jsp。接下來(lái)咱們就看看如何利用Thymeleaf模板引擎寫(xiě)出優(yōu)雅的html代碼。

1.1 添加Maven依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

可以查看依賴關(guān)系,發(fā)現(xiàn)spring-boot-starter-thymeleaf下面已經(jīng)包括了spring-boot-starter-web,所以可以把spring-boot-starter-web的依賴去掉.

1.2 改造html代碼

接下來(lái)我們以login登錄界面來(lái)談?wù)凾hymeleaf模板引擎的使用方法,
還是以上一篇博客《Spring boot(三):@RequestMapping之Form表單參數(shù)傳遞及POJO綁定實(shí)例講解》的工程項(xiàng)目代碼為基礎(chǔ),改造一下我們的登錄界面

<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="utf-8"/>
    
    <title>Login</title>
    
    <link rel="stylesheet" href="/SpringBootBase/css/bootstrap.min.css"/>
    <link rel="stylesheet" href="/SpringBootBase/css/customer/login.css"/>
</head>

<body>
    <div class="container">
        <form class="form-signin" action="./login" method="post">
            <h2 class="form-signin-heading">請(qǐng) 登 錄</h2>
            <input type="text" class="form-control" placeholder="賬號(hào)" name="username"/>
            <input type="password" class="form-control" placeholder="密碼" name="password"/> 
            <button class="btn btn-lg btn-primary btn-block" type="submit">登錄</button>
        </form>
    </div>
</body>
</html>

1.2.1 xmlns:th命名空間

使用Thymeleaf引擎需要在html標(biāo)簽添加Thymeleaf模板引擎的命名空間:xmlns:th="http://www.thymeleaf.org",這樣的話才可以在其他標(biāo)簽里面使用th:*這樣的語(yǔ)法.這是下面語(yǔ)法的前提。

1.2.2 th:href="@{...}"的使用

引用的絕對(duì)路徑也可以用模板改造,“@{}”為引用靜態(tài)資源文件,如:

<link rel="stylesheet" href="/SpringBootBase/css/bootstrap.min.css"/>
<link rel="stylesheet" href="/SpringBootBase/css/customer/login.css"/>

可以用thymeleaf模板改寫(xiě)為@{}的形式表示

<link rel="stylesheet" th:href="@{css/bootstrap.min.css}"/>
<link rel="stylesheet" th:href="@{css/customer/login.css}"/>

會(huì)引入/static目錄下的/css/下的文件;

1.2.3 th:action="@{...}"的使用

表單POST的action url也可以用@{}表示:如

<form class="form-signin" action="./login" method="post">
    ...
</form>
<form class="form-signin" th:action="@{/login}" method="post">
    ...
</form>

于是改造完成后的代碼就變成了這樣:

<!DOCTYPE html>
<html lang="zh-cn" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8"/>
    
    <title>Login</title>
    
    <link rel="stylesheet" th:href="@{css/bootstrap.min.css}"/>
    <link rel="stylesheet" th:href="@{css/customer/login.css}"/>
</head>

<body>
    <div class="container">
        <form class="form-signin" th:action="@{/login}" method="post">
            <h2 class="form-signin-heading">請(qǐng) 登 錄</h2>
            <input type="text" class="form-control" placeholder="賬號(hào)" name="username"/>
            <input type="password" class="form-control" placeholder="密碼" name="password"/> 
            <button class="btn btn-lg btn-primary btn-block" type="submit">登錄</button>
        </form>
    </div>
</body>
</html>

我們?cè)賮?lái)運(yùn)行一下,得到如下圖結(jié)果:


圖1

發(fā)現(xiàn)與我們上一篇的博客運(yùn)行的結(jié)果不一致了,css樣式找不到了,為什么會(huì)這樣呢?
因?yàn)镾pring Boot默認(rèn)掃描的Thymeleaf的模板路徑為resources/templates/,而此時(shí)我們的index.html在webapp目錄下。
接下來(lái)我們將index.html移到resources/templates/目錄下,并再寫(xiě)個(gè)controller,將根目錄的訪問(wèn)都重定向到resources/templates/index.html
LoginController代碼:

@RequestMapping(value ="/", method = RequestMethod.GET)
String home() {
    return "index";
}

運(yùn)行一下,結(jié)果正常
輸入用戶名及密碼,后臺(tái)也如期打印出

POJO: tech.onroad.springbootbase.bean.UserVO, hash code: 1537182416, userame: admin, password: 123456

1.3 th:object="${...}"與th:field="*{...}"的使用

${...}用于獲取變量值,對(duì)于javaBean的話使用變量名.屬性名,如${user.name}
舉個(gè)例子,如若需要將后臺(tái)的值回顯到前臺(tái),那應(yīng)該怎么做,此時(shí)th:object="${...}"與th:field="*{...}"就派上用場(chǎng)了。

<form class="form-signin" th:action="@{/login}" th:object="${user}" method="post">
    <h2 class="form-signin-heading">請(qǐng) 登 錄</h2>
    <input type="text" class="form-control" placeholder="賬號(hào)" th:field="*{username}"></input>
    <input type="password" class="form-control" placeholder="密碼" th:field="*{password}"></input> 
    <button class="btn btn-lg btn-primary btn-block" type="submit">登錄</button>
</form>

在表單代碼中增加th:object屬性,將name屬性換成th:field屬性,其中th:object定義表單數(shù)據(jù)提交對(duì)象user,用th:field定義表單數(shù)據(jù)屬性,用*{}鎖定上級(jí)定義的對(duì)象,{}內(nèi)填寫(xiě)對(duì)象屬性,提交表單時(shí)自動(dòng)將屬性值注入到對(duì)象中。
那前臺(tái)如何知道th:object="${user}"與后臺(tái)的哪個(gè)Java Bean對(duì)應(yīng)呢?在controller代碼里就可以看出端倪。

@RequestMapping(value ="/", method = RequestMethod.GET)
String home(Model model, UserVO user) {
    model.addAttribute("user", user);
    return "index";
}

@RequestMapping(value = "login", method = RequestMethod.POST)
public String login(Model model, UserVO user){
    System.out.println("POJO: " + user.getClass().getName() + 
            ", hash code: " + user.hashCode() + ", " + user.toString());
    model.addAttribute("user", user);
    return "index";
}

相比于前面的代碼,我們多了model.addAttribute("user", user); 也就是說(shuō)這個(gè)user對(duì)象是從后臺(tái)通過(guò)Model傳遞過(guò)來(lái)的,當(dāng)然也就能識(shí)別啦。
我們來(lái)運(yùn)行一下,輸入https://localhost:8443/SpringBootBase/得到如下界面:

圖2

輸入用戶名admin及密碼123456,點(diǎn)擊登錄,得到如下圖結(jié)果


圖3

發(fā)現(xiàn)瀏覽器地址欄的URL已經(jīng)變?yōu)?a target="_blank" rel="nofollow">https://localhost:8443/SpringBootBase/login,且賬戶名admin還被顯示著,說(shuō)明我們的前臺(tái)已能正確接收后臺(tái)傳遞過(guò)來(lái)的變量值了。至于密碼欄為什么被清空,那是因?yàn)槊艽a框這個(gè)input的type="password"所致。

Thymeleaf模板引擎還有非常多的語(yǔ)法,如判斷條件th:if, th:unless;th:inline,...... 以后若需要詳細(xì)介紹及demo,再慢慢更新。

最后建議在application.properties配置關(guān)閉thymeleaf緩存,因?yàn)镾pring Boot使用thymeleaf時(shí)默認(rèn)是有緩存的,即你把一個(gè)頁(yè)面代碼改了不會(huì)刷新頁(yè)面的效果,你必須重新運(yùn)行spring-boot的main()方法才能看到頁(yè)面更改的效果。

spring.thymeleaf.cache: false

完整代碼可到我的github下載:
https://github.com/onroadtech/SpringbootBase/
tag: spring_boot_thymeleaf
commit-id: 35860470354212e14da0af993025b6555ff917ac


本博文已同步發(fā)表于我的個(gè)人博客網(wǎng)站,歡迎轉(zhuǎn)載指正并注明出處。
個(gè)人博客: www.onroad.tech
指正郵箱: onroad_tech@163.com

最后編輯于
?著作權(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)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

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