1. freemarker引擎的使用
如果你使用的是idea或者eclipse中安裝了sts插件,那么在新建項目時就可以直接指定試圖模板
如圖:
勾選freeMarker,此時springboot項目中就會自動引入freemarker的依賴如下:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency>
如果不是idea且eclipse也沒有插件,那么就需要手動添加這個依賴到pom文件中。
springboot存放模板和靜態文件目錄結構如下:
templates中存放模板文件,static中存放一些靜態文件,如圖片,css,js等
templates在springboot中默認為模板根目錄,static默認為靜態文件根目錄,所以我們在寫路徑的時候不用將這兩個目錄路徑寫到訪問目錄中。
不需要任何配置,只需要一個controller接口,就可以直接使用controller和模板直接進行交互,直接上代碼
IndexController接口:
package com.wangx.boot.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import java.util.Map; @Controller @RequestMapping("/index") public class IndexController { @RequestMapping("/index") public String hello(Map<String,Object> map){ //傳遞數據到freemaker模板中 map.put("name", "[Angel -- 守護天使]"); return "index"; } }
freemarker模板文件的默認后綴名為ftl.
index.ftl
<!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>
<p>
<!--獲取后台傳過來的數據-->
<p>${name}</p>
</p>
</body>
</html>
當請求返回index時,springboot會根據這個路徑到templates目錄下自動匹配這個模板引擎,這樣就完成了后台到模板的整合和數據交互。
結果如下:
如果想要訪問靜態資源時,如圖片,直接寫上絕對路徑<img src="/1.jpg">即可(注意在Controller方法返回值中盡量寫相對路徑,即不要帶/,否則在linux環境下中可能會出錯)。
2. thymeleaf
thymeleaf的使用與freemarker很相似,簡單的使用只需要將示例1中的ftl改為html文件,取值方式改為thymeleaf即可,這里只展示thymeleaf的html代碼,其他的代碼跟freemarker一樣,只是在創建項目時選擇thymeleaf或在pom文件中添加thymeleaf依賴即可。
index.html:
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Hello World!</title> </head> <body> <p th:text="${name}"> <img src="1.jpg"> </p> </body> </html>
啟動項目,訪問http://localhost:8080/index/index,結果與1相同。
這里只是簡單的展示怎么整合springboot和模板引擎的整合,模板引擎的具體使用方式請參照官網。
freemarker官方文檔:https://freemarker.apache.org/docs/
thymeleaf:官方文檔:https://www.thymeleaf.org/
在springboot官方推薦使用的是thymeleaf模板,因為現在的趨勢都是前后端分離的架構,所以使用thymeleaf耦合性會更低。