javascript
java 模板引擎_SpringBoot入门系列(四)如何整合Thymeleaf模板引擎
前面介紹了Spring Boot的優點,然后介紹了如何快速創建Spring Boot 項目。不清楚的朋友可以看看之前的文章:https://www.cnblogs.com/zhangweizhong/category/1657780.html。
今天我們主要來看看 Thymeleaf 在 Spring Boot 中的整合!
Thymeleaf 簡介
Spring Boot 2主要支持頁面模板是 Thymeleaf 和 Freemarker ,當然,作為 Java 最最基本的頁面模板 Jsp ,Spring Boot 也是支持的,只是使用比較麻煩。
Thymeleaf 作為新一代 Java 模板引擎,它的功能與 Velocity、FreeMarker 等傳統 Java 模板引擎比較類似,但是Thymeleaf 模板后綴為 .html,可以直接被瀏覽器打開,因此,開發時非常方便。
它既可以讓前端工程師在瀏覽器中直接打開查看樣式,也可以讓后端工程師結合真實數據查看顯示效果,同時,SpringBoot 提供了 Thymeleaf 自動化配置解決方案,因此在 SpringBoot 中使用 Thymeleaf 非常方便。
事實上, Thymeleaf 除了展示基本的 HTML ,進行頁面渲染之外,也可以作為一個 HTML 片段進行渲染,例如我們在做郵件發送時,可以使用 Thymeleaf 作為郵件發送模板。
整合
新項目整合 Thymeleaf 非常容易,只需要創建項目時勾上 Thymeleaf 即可,這里就不說了。
下面說說怎么在現有的項目中手動整合Thymeleaf:
1、在pom.xml 增加依賴如下:
org.springframework.boot spring-boot-starter-data-redis 1.5.7.RELEASE2、application.properties 文件增加Thymeleaf 相關配置
############################################################## thymeleaf 模板#############################################################spring.thymeleaf.prefix=classpath:/templates/spring.thymeleaf.suffix=.htmlspring.thymeleaf.mode=HTMLspring.thymeleaf.encoding=UTF-8spring.thymeleaf.servlet.content-type=text/html# 關閉緩存spring.thymeleaf.cache=falsespring.thymeleaf.prefix 指定模板頁面的路徑3、增加前臺頁面
在resourceemplateshymeleaf 目錄下增加index.html 頁面
Thymeleaf模板引擎hello Spring Boot~~~~~~~
th:text 就是Thymeleaf的標簽,用于處理標簽體的文本內容。
其他更對的標簽及用法,我會在下一篇文章中介紹。
4、創建 Controller
接下來我們就可以創建 Controller 了,實際上引入 Thymeleaf 依賴之后,我們可以不做任何配置。新建的ThymeleafController如下:
package com.weiz.controller;import java.util.ArrayList;import java.util.Date;import java.util.List;import org.springframework.stereotype.Controller;import org.springframework.ui.ModelMap;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestMapping;import com.weiz.pojo.User;@Controller@RequestMapping("th")public class ThymeleafController { @RequestMapping("/index") public String index(ModelMap map) { map.addAttribute("name", "thymeleaf-index"); return "thymeleaf/index"; }}在ThymeleafController 中返回邏輯視圖名,邏輯視圖名為 index ,意思我們需要在 resources/templates/thymeleaf 目錄下提供一個名為 index.html 的 Thymeleaf 模板文件。
5、運行效果
在瀏覽器中輸入:http://localhost:8080/th/index 查看頁面返回結果。
總結
主要向大家簡單介紹了 Spring Boot 整合 Thymeleaf,還是比較簡單的。下一篇文章會給大家詳細介紹Thymeleaf的常用標簽和用法。大家也可以閱讀 Thymeleaf 官方文檔學習 Thymeleaf 的更多用法。
總結
以上是生活随笔為你收集整理的java 模板引擎_SpringBoot入门系列(四)如何整合Thymeleaf模板引擎的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python tkinter_Pytho
- 下一篇: 百度地图手机和电脑不一致_如何解决电脑显