1. 程式人生 > >SpringBoot(三)——使用Thymeleaf模板

SpringBoot(三)——使用Thymeleaf模板

thymeleaf是一種和FreeMarker類似,在後臺生成UI的JAVA模板引擎,可以替代JSP。同時thymeleaf也是SpringBoot推薦的解決方案,在這裡先不討論優劣,只是簡單介紹一下它的特點和簡單的使用。

一 特點

  1. 允許定義多種型別模板
    • HTML
    • XML
    • TEXT
    • JAVASCRIPT
    • CSS
    • RAW
  2. 完整HTML5標誌支援:Thymeleaf 3.0 不再是基於XML結構的。由於引入新的解析引擎,模板的內容格式不再需要嚴格遵守XML規範。即不在要求標籤閉合,屬性加引號等等。
  3. 片段(Fragment)表示式。
  4. 新的方言系統。

二 使用

1、 配置

首先在專案的pom.xml中新增依賴,因為Spring預設使用就是Thymeleaf模板引擎,因此只需要新增如下依賴即可。

<!-- Thymeleaf模板依賴配置 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

PS:SpringBoot–1.5.8RELEASE預設為Thyleaf2.1版本,按照官方文件給的提示,將版本號改為3.0,方言改為2.1。不然可能會報一些異常。

By default, spring-boot-starter-thymeleaf uses Thymeleaf 2.1. If you
are using the spring-boot-starter-parent, you can use Thymeleaf 3 by
overriding the thymeleaf.version and thymeleaf-layout-dialect.version
properties, for example:

<properties
>
<thymeleaf.version>3.0.2.RELEASE</thymeleaf.version> <thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version> </properties>

然後在application.yml中新增配置資訊,當然在application.properties中也是一樣的。最主要的就是開發的時候記得關閉快取。

    thymeleaf:
        suffix: .html
        mode: HTML5
        encoding: UTF-8
        content-type: text/html
        #開發時關閉快取,頁面的更新
        cache: false

2、新建模板檔案

在這裡使用了變數${hello},會根據執行時後臺傳的引數替換這裡的內容。

    <!DOCTYPE html>  
    <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"  
          xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">  
        <head>  
            <title>Hello World!</title>  
        </head>  
        <body>  
            <h1 th:inline="text">Hello.v.2</h1>  
            <p th:text="${hello}"></p>  
        </body>  
    </html>  

3、新建Controller

新建Controller,注意這裡一定要用@Controller而不是@RestController 並且不能使用 @ResponseBody 註解

@Controller  

publicclass TemplateController {  

    @RequestMapping("/hello")  
    public String Welcome(Model model){
        model.addAttribute("hello", "你好");
        return "hello";
    }
}  

4、啟動專案並且訪問

這裡寫圖片描述