更新時間:2021-06-29 17:03:10 來源:動力節(jié)點(diǎn) 瀏覽1361次
Thymeleaf是跟Velocity、FreeMarker類似的模板引擎,它可以完全替代JSP,相較與其他的模板引擎,它主要有以下幾個特點(diǎn):
1.Thymeleaf在有網(wǎng)絡(luò)和無網(wǎng)絡(luò)的環(huán)境下皆可運(yùn)行,即它可以讓美工在瀏覽器查看頁面的靜態(tài)效果,也可以讓程序員在服務(wù)器查看帶數(shù)據(jù)的動態(tài)頁面效果。這是由于它支持html原型,然后在html標(biāo)簽里增加額外的屬性來達(dá)到模板+數(shù)據(jù)的展示方式。瀏覽器解釋html時會忽略未定義的標(biāo)簽屬性,所以thymeleaf的模板可以靜態(tài)地運(yùn)行;當(dāng)有數(shù)據(jù)返回到頁面時,Thymeleaf標(biāo)簽會動態(tài)地替換掉靜態(tài)內(nèi)容,使頁面動態(tài)顯示。
2.Thymeleaf開箱即用的特性。它提供標(biāo)準(zhǔn)和spring標(biāo)準(zhǔn)兩種方言,可以直接套用模板實(shí)現(xiàn)JSTL、OGNL表達(dá)式效果,避免每天套模板、改jstl、改標(biāo)簽的困擾。同時開發(fā)人員也可以擴(kuò)展和創(chuàng)建自定義的方言。
3.Thymeleaf提供spring標(biāo)準(zhǔn)方言和一個與SpringMVC完美集成的可選模塊,可以快速的實(shí)現(xiàn)表單綁定、屬性編輯器、國際化等功能。
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. 啟動項(xiàng)目,訪問http://localhost:8080/hello,看到如下顯示證明SpringBoot整合Thymeleaf成功。
以上就是動力節(jié)點(diǎn)小編介紹的"SpringBoot整合Thymeleaf模板引擎",希望對大家有幫助,想了解更多可查看Thymeleaf基礎(chǔ)教程技術(shù)文檔,如有疑問,請?jiān)诰€咨詢,有專業(yè)老師隨時為您服務(wù)。
初級 202925
初級 203221
初級 202629
初級 203743