更新時間:2021-06-29 17:03:10 來源:動力節點 瀏覽1232次
Thymeleaf是跟Velocity、FreeMarker類似的模板引擎,它可以完全替代JSP,相較與其他的模板引擎,它主要有以下幾個特點:
1.Thymeleaf在有網絡和無網絡的環境下皆可運行,即它可以讓美工在瀏覽器查看頁面的靜態效果,也可以讓程序員在服務器查看帶數據的動態頁面效果。這是由于它支持html原型,然后在html標簽里增加額外的屬性來達到模板+數據的展示方式。瀏覽器解釋html時會忽略未定義的標簽屬性,所以thymeleaf的模板可以靜態地運行;當有數據返回到頁面時,Thymeleaf標簽會動態地替換掉靜態內容,使頁面動態顯示。
2.Thymeleaf開箱即用的特性。它提供標準和spring標準兩種方言,可以直接套用模板實現JSTL、OGNL表達式效果,避免每天套模板、改jstl、改標簽的困擾。同時開發人員也可以擴展和創建自定義的方言。
3.Thymeleaf提供spring標準方言和一個與SpringMVC完美集成的可選模塊,可以快速的實現表單綁定、屬性編輯器、國際化等功能。
1.在pom.xml文件引入thymeleaf
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2. 在application.properties(application.yml)文件中配置thymeleaf
# thymeleaf
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.check-template-location=true
spring.thymeleaf.suffix=.html
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.cache=false
3. 新建編輯控制層代碼HelloController,在request添加了name屬性,返回到前端hello.html再使用thymeleaf取值顯示。
@Controller
public class HelloController {
@RequestMapping("/hello")
public String hello(HttpServletRequest request, @RequestParam(value = "name", defaultValue = "springboot-thymeleaf") String name) {
request.setAttribute("name", name);
return "hello";
}
}
4. 新建編輯模板文件,在resources文件夾下的templates目錄,用于存放HTML等模板文件,在這新增hello.html,添加如下代碼。
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>springboot-thymeleaf demo</title>
</head>
<body>
<p th:text="'hello, ' + ${name} + '!'" />
</body>
</html>
切記:使用Thymeleaf模板引擎時,必須在html文件上方添加該行代碼使用支持Thymeleaf。
<html lang="en" xmlns:th="http://www.thymeleaf.org">
5. 啟動項目,訪問http://localhost:8080/hello,看到如下顯示證明SpringBoot整合Thymeleaf成功。
以上就是動力節點小編介紹的"SpringBoot整合Thymeleaf模板引擎",希望對大家有幫助,想了解更多可查看Thymeleaf基礎教程技術文檔,如有疑問,請在線咨詢,有專業老師隨時為您服務。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習