1. 程式人生 > >《SpringBoot從入門到放棄》之第(四)篇——開發Web應用之模板Thymeleaf、FreeMarker

《SpringBoot從入門到放棄》之第(四)篇——開發Web應用之模板Thymeleaf、FreeMarker

 

SpringBoot提供了預設配置的模板引擎主要有以下幾種:Thymeleaf、FreeMarker、Velocity、Groovy、Mustache

預設的建立SpringBoot專案時,開發工具就幫我們建立好了src/main/resources/static目錄,該位置存放常用的靜態資源,如js、css、圖片等。src/main/resources/templates 存放模板檔案。

1、thymeleaf

Thymeleaf是一個XML/XHTML/HTML5模板引擎,可用於Web與非Web環境中的應用開發,它是一個開源的Java庫。

示例:

在pom.xml 中新增 thymeleaf 依賴,如果之前沒有 web 依賴也一起新增,然後重新載入 jar 依賴:

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

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

在 src/main/resources/templates 目錄下建立 myIndex.html 檔案

內容如下:注意 thymeleaf 的語法。如果想接觸 thymeleaf ,可以參考簡書的:Thymeleaf 簡易教程

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>SpringBoot測試thymeleaf模板</title>
</head>
<body>
    使用者:<h2 th:text="${name}"></h2>
    描述:<h2 th:text="${desc}"></h2>
</body>
</html>

編寫 ThymeleafController java類:

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

@Controller //不是使用 ResController
public class ThymeleafController {

    @RequestMapping("/thy")
    public String thymeleaf(ModelMap map){
        map.addAttribute("name","流放深圳");
        map.addAttribute("desc","讓天下沒有難寫的程式碼");
        return "myIndex";//返回的是html的檔名
    }
}

啟動服務,瀏覽器地址訪問(根據自己配置的埠號來訪問):http://localhost:9090/thy

說明:如果需要修改 html的內容,也需要重新服務,因為 thymeleaf 是需要編譯的。

 

2、freeMarker

在pom.xml 配置檔案中新增如下配置,然後重新載入 jar 依賴:

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

在 src/main/resources/templates 目錄下建立 myFreeMarker.ftl 檔案 (技巧:先建立 html 檔案,再重新命名 .ftl)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>SpringBoot測試freeMarker模板</title>
</head>
<body>
<h2>${name}</h2>
<h2>${desc}</h2>
</body>
</html>

然後編寫 FreeMarkerController 類(實際上跟ThymeleafController 程式碼一樣,為了學習,最好有明顯的區分。如 url 對映)

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

@Controller //不是使用 ResController
public class FreeMarkerController {

    @RequestMapping("/free")
    public String thymeleaf(ModelMap map){
        map.addAttribute("name","流放深圳");
        map.addAttribute("desc","讓天下沒有難寫的程式碼");
        return "myFreeMarker";//返回的是html的檔名
    }
}

啟動服務,瀏覽器地址訪問(根據自己配置的埠號來訪問):http://localhost:9090/free