javascript
SpringBoot学习笔记(4)----SpringBoot中freemarker、thymeleaf的使用
1. freemarker引擎的使用
如果你使用的是idea或者eclipse中安裝了sts插件,那么在新建項(xiàng)目時(shí)就可以直接指定試圖模板
如圖:
勾選freeMarker,此時(shí)springboot項(xiàng)目中就會(huì)自動(dòng)引入freemarker的依賴如下:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-freemarker</artifactId></dependency>
如果不是idea且eclipse也沒有插件,那么就需要手動(dòng)添加這個(gè)依賴到pom文件中。
springboot存放模板和靜態(tài)文件目錄結(jié)構(gòu)如下:
templates中存放模板文件,static中存放一些靜態(tài)文件,如圖片,css,js等
templates在springboot中默認(rèn)為模板根目錄,static默認(rèn)為靜態(tài)文件根目錄,所以我們在寫路徑的時(shí)候不用將這兩個(gè)目錄路徑寫到訪問目錄中。
不需要任何配置,只需要一個(gè)controller接口,就可以直接使用controller和模板直接進(jìn)行交互,直接上代碼
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){ //傳遞數(shù)據(jù)到freemaker模板中 map.put("name", "[Angel -- 守護(hù)天使]"); return "index"; } }freemarker模板文件的默認(rèn)后綴名為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><!--獲取后臺(tái)傳過來的數(shù)據(jù)--><p>${name}</p> </p> </body> </html>當(dāng)請求返回index時(shí),springboot會(huì)根據(jù)這個(gè)路徑到templates目錄下自動(dòng)匹配這個(gè)模板引擎,這樣就完成了后臺(tái)到模板的整合和數(shù)據(jù)交互。
結(jié)果如下:
如果想要訪問靜態(tài)資源時(shí),如圖片,直接寫上絕對路徑<img src="/1.jpg">即可(注意在Controller方法返回值中盡量寫相對路徑,即不要帶/,否則在linux環(huán)境下中可能會(huì)出錯(cuò))。
2. thymeleaf
thymeleaf的使用與freemarker很相似,簡單的使用只需要將示例1中的ftl改為html文件,取值方式改為thymeleaf即可,這里只展示thymeleaf的html代碼,其他的代碼跟freemarker一樣,只是在創(chuàng)建項(xiàng)目時(shí)選擇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>啟動(dòng)項(xiàng)目,訪問http://localhost:8080/index/index,結(jié)果與1相同。
這里只是簡單的展示怎么整合springboot和模板引擎的整合,模板引擎的具體使用方式請參照官網(wǎng)。
freemarker官方文檔:https://freemarker.apache.org/docs/
thymeleaf:官方文檔:https://www.thymeleaf.org/
在springboot官方推薦使用的是thymeleaf模板,因?yàn)楝F(xiàn)在的趨勢都是前后端分離的架構(gòu),所以使用thymeleaf耦合性會(huì)更低。
?
原文 SpringBoot學(xué)習(xí)筆記(4)----SpringBoot中freemarker、thymeleaf的使用
轉(zhuǎn)載于:https://www.cnblogs.com/xiaoshen666/p/10843930.html
總結(jié)
以上是生活随笔為你收集整理的SpringBoot学习笔记(4)----SpringBoot中freemarker、thymeleaf的使用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: P3870 [TJOI2009]开关
- 下一篇: SpringBoot 2.x (12):