【Springboot】Springboot整合Thymeleaf模板引擎


Thymeleaf

Thymeleaf是跟Velocity、FreeMarker類似的模板引擎,它可以完全替代JSP,相較與其他的模板引擎,它主要有以下幾個特點:

1. Thymeleaf在有網絡和無網絡的環境下皆可運行,即它可以讓美工在瀏覽器查看頁面的靜態效果,也可以讓程序員在服務器查看帶數據的動態頁面效果。這是由於它支持 html 原型,然后在 html 標簽里增加額外的屬性來達到模板+數據的展示方式。瀏覽器解釋 html 時會忽略未定義的標簽屬性,所以thymeleaf的模板可以靜態地運行;當有數據返回到頁面時,Thymeleaf 標簽會動態地替換掉靜態內容,使頁面動態顯示。

2. Thymeleaf開箱即用的特性。它提供標准和spring標准兩種方言,可以直接套用模板實現JSTL、OGNL表達式效果,避免每天套模板、改jstl、改標簽的困擾。同時開發人員也可以擴展和創建自定義的方言。

3. Thymeleaf提供spring標准方言和一個與SpringMVC完美集成的可選模塊,可以快速的實現表單綁定、屬性編輯器、國際化等功能。

Thymeleaf官網:http://www.thymeleaf.org

 

Thymeleaf整合SpringBoot

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成功。

 

 

 作者注:原文發表在公號(點擊查看),目前就職阿里,定期分享IT互聯網、金融等工作經驗心得、人生感悟,歡迎訂閱交流,需要大廠內推的也可到公號砸簡歷。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM