Spring Boot模板引擎實戰——Thymeleaf
一 點睛
1 靜態資源訪問
在我們開發Web應用的時候,需要引用大量的js、css、圖片等靜態資源。
2 預設配置
Spring Boot預設提供靜態資源目錄位置需置於classpath下,目錄名需符合如下規則:
-
/static
-
/public
-
/resources
-
/META-INF/resources
3 模板引擎
Spring Boot提供了預設配置的模板引擎主要有以下幾種:
-
Thymeleaf
-
FreeMarker
-
Velocity
-
Groovy
-
Mustache
Spring Boot建議使用這些模板引擎,避免使用JSP,若一定要使用JSP將無法實現Spring Boot的多種特性。
當你使用上述模板引擎中的任何一個,它們預設的模板配置路徑為:src/main/resources/templates。
4 Thymeleaf
Thymeleaf是一個XML/XHTML/HTML5模板引擎,可用於Web與非Web環境中的應用開發。它是一個開源的Java庫,基於Apache License 2.0許可,由Daniel Fernández建立,該作者還是Java加密庫Jasypt的作者。
Thymeleaf提供了一個用於整合Spring MVC的可選模組,在應用開發中,你可以使用Thymeleaf來完全代替JSP或其他模板引擎,如Velocity、FreeMarker等。Thymeleaf的主要目標在於提供一種可被瀏覽器正確顯示的、格式良好的模板建立方式,因此也可以用作靜態建模。你可以使用它建立經過驗證的XML與HTML模板。相對於編寫邏輯或程式碼,開發者只需將標籤屬性新增到模板中即可。接下來,這些標籤屬性就會在DOM(文件物件模型)上執行預先制定好的邏輯。
Thymeleaf主要以屬性的方式加入到html標籤中,瀏覽器在解析html時,當檢查到沒有的屬性時候會忽略,所以Thymeleaf的模板可以通過瀏覽器直接開啟展現,這樣非常有利於前後端的分離。
二 實戰
1 控制類
package com.didispace.web; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @Controller public class HelloController { @ResponseBody @RequestMapping("/hello") public String hello() { return "Hello World"; } @RequestMapping("/") public String index(ModelMap map) { map.addAttribute("host", "http://blog.didispace.com"); return "index"; } }
2 啟動類
package com.didispace;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
3 模板
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8" />
<title></title>
</head>
<body>
<!--h1中的hello world被替換了-->
<h1 th:text="${host}">Hello World</h1>
<!--h2保持原樣-->
<h2>hello world</h2>
</body>
</html>
4 新增依賴
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<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>
</dependencies>
三 測試
1 瀏覽器輸入 http://localhost:8080/
四 參考
http://blog.didispace.com/springbootweb/
https://www.cnblogs.com/jiangbei/p/8462294.html