SpringBoot入門系列篇(五):簡單使用thymleaf模板

前情提要

使用過vue.js的人都知道它的數據綁定是多麼的方便,其實通過純js,我們也可以實現這種操作,通過Ajax異步獲取數據並放入相應的元素中,而在SpringBoot中,也同樣提供了數據綁定的實現,通過使用thymleaf模板,可以實現類似於vue.js那樣的數據綁定,只需要訪問一個url,就能動態獲取裏面的所有數據


SpringBoot使用thymleaf模板的簡單實例

首先,我們需要引入thymleaf模板的依賴,SpringBoot默認使用的就是thymleaf,所以我們在pom.xml中引入如下:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
然後創建一個Controller類,這裏需要注意的是:Controller類的修飾註解不是@RestController,而是@Controller,他們的區別可以去百度:
package org.framework.demo.section1;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Map;

/**
 * 使用模板
 * @author chengxi
 */
@Controller
public class TemplateController {

    @RequestMapping("/temp")
    public String gettemp(Map<String,String> map){

        map.put("info","hello thymeleaf");
        return "/temp1";
    }
}
接下來就需要創建模板文件了,上面的請求對應的模板文件就是classpath: templates/temp1.html,默認是html文件,然後我們在resources目錄下面創建templates文件夾,該文件夾是SprignBoot模板文件默認的目錄,在該目錄下面創建temp1.html,如果想要使用請求處理方法中map注入的info可以在temp1.html文件中寫入如下代碼:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <title>Hello HTML</title>
</head>
<body>
    <h1 th:text="${info}"></h1>
</body>
</html>
在html中thymleaf模板的使用類似於vue.js
接下來,啓動tomcat測試類,輸入網址:localhost:8080/temp就會看到輸出的頁面是我們編寫的temp1.html文件


初使用thymleaf的404錯誤:meta

這裏需要注意的是,使用thymleaf模板時,創建的html文件是在classpath:templates目錄下的,而且SpringBoot中使用的是Thymleaf2.0版本的,所以所解析的不是基於html的,而是基於xml的,因此<meta ...>這類的標籤會報錯404,有兩種方式,改成<meta ... />或者修改SpringBoot默認的thymleaf模板版本爲3.0,具體的可以參考優秀博客: springboot中使用thymeleaf模板

thymleaf模板文件中引入外部文件

在thymleaf模板中引入外部的js/css/img文件時,對應的文件是放在classpath: static目錄下面的,因此我們使用外部的js、css、img文件時需要創建與templates同級的static並放到這裏面,目錄使用的方式爲:/js/index.js格式,具體可以參考優秀博客:springBoot項目中使用了thymeleaf模板,怎麼在html文件中調用外部的.js文件

thymleaf模板文件的實時編輯

在使用thymleaf模板的時候,我們會發現一個問題,就是我們引入了html文件之後,在不重啓項目的情況下改變html文件,然後保存,刷新頁面,效果仍然沒變,這是因爲thmyleaf的緩存導致的,要想實時改變,就需要關閉thymleaf的緩存,關閉的方式很簡單,在application.properties屬性配置文件中添加如下一行代碼:
spring.thymleaf.cache = false
這樣一來,就能關閉thymleaf的緩存,從而實現實時編輯html文件了
發佈了207 篇原創文章 · 獲贊 75 · 訪問量 36萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章