javascript
九、SpringBoot集成Thymeleaf模板引擎
Thymeleaf咋讀!???
呵呵,是不是一臉懵逼。。。哥用我的大學四級英文知識告訴你吧:[θaimlif]。
啥玩意?不會音標?...那你就這樣叫它吧:“賽母李府”,大部分中國人是聽不出破綻的。。。。
Thymeleaf是啥?
四個字:頁面模板(有道翻譯結果)
就是在頁面里面導入一些特有的標簽和表達式,幫助我們更好地渲染頁面
個人理解:
Thyme:百里香。leaf:葉子;
百里香是啥玩意?
經過上面的觀察和分析,我感覺Thymeleaf的創作者是一個很有“生活”的人,我們看到上面圖片上的百里香,一片一片的鮮翠的葉子很和諧的長在不同的枝頭就好比我們的一個個HTML“葉面”分別存放在不同的文件夾下面,她們雖然在不同的枝頭,但是她們的模樣都很相似,這些相似點就是模板。。。
好了,哥敢用哥的一包花生米和一瓶啤酒打賭!!!如果你有幸閱讀到哥的這篇文章,那么這絕逼是你見過對Thymeleaf最最最牛X的介紹。。。
官方介紹:https://www.thymeleaf.org/
Thymeleaf能夠處理HTML,XML,JavaScript,CSS甚至純文本。
看了上面的官方解釋是不是更是一臉懵逼。。。那就不要糾結了,我們下面直接看她到底怎么用,用來干什么,這樣你不就知道Thymeleaf是啥了嗎
SpringBoot集成Thymeleaf:
首先為了大家看的不懵逼,我先展開一下整體項目結構:
?
1、pom.xml 添加 Thymeleaf 模板引擎
<!--thymeleaf模板--> <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>2、application.properties 配置 Thymeleaf 信息
#下面是thymeleaf配置 # 啟用緩存:建議生產開啟 spring.thymeleaf.cache=false # 建議模版是否存在 spring.thymeleaf.check-template-location=true # Content-Type 值 spring.thymeleaf.servlet.content-type=text/html # 是否啟用 spring.thymeleaf.enabled=true # 模版編碼 spring.thymeleaf.encoding=utf-8 # 應該從解析中排除的視圖名稱列表(用逗號分隔) spring.thymeleaf.excluded-view-names= # 模版模式 spring.thymeleaf.mode=HTML5 # 模版存放路徑 spring.thymeleaf.prefix=classpath:/templates/ # 模版后綴 spring.thymeleaf.suffix=.html3、創建controller類,編寫代碼
?我們創建ThymeleafTest.java,代碼如下:
@Controller @RequestMapping("/thymeleafTest") public class ThymeleafTest {@RequestMapping("/testThymeleaf")public ModelAndView testThymeleaf(){ModelAndView modelAndView=new ModelAndView("/thymeleaf");modelAndView.addObject("user","任正非");return modelAndView;} }4、 創建模板,編寫html代碼
我們在resources/templates下創建index.html,代碼如下:
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>thymeleaf測試頁面</title> </head> <body> <h1 th:text="${user}"></h1> </body> </html>?啟動項目然后訪問:
至此thymeleaf就成功集成了,是不是很開心。。呵呵,但是你別高興的太早了,,,此時你會發現你之前配置成功的JSP頁面現在不能訪問了
關于這個問題的解決請參考鄙人的另一篇博客:
https://www.cnblogs.com/luzhanshi/p/10925851.html
?
轉載于:https://www.cnblogs.com/luzhanshi/p/10928501.html
總結
以上是生活随笔為你收集整理的九、SpringBoot集成Thymeleaf模板引擎的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Codeforces Round #20
- 下一篇: 学习opencv(1)