thymeleaf介紹
Thymeleaf是現(xiàn)代化服務(wù)器端的Java模板引擎,不同與其它幾種模板的是Thymeleaf的語(yǔ)法更加接近HTML,并且具有很高的擴(kuò)展性。詳細(xì)資料可以瀏覽官網(wǎng)。

Thymeleaf特點(diǎn)
- 支持無(wú)網(wǎng)絡(luò)環(huán)境下運(yùn)行,由于它支持 html 原型,然后在 html 標(biāo)簽里增加額外的屬性來(lái)達(dá)到模板+數(shù)據(jù)的展示方式。瀏覽器解釋 html 時(shí)會(huì)忽略未定義的標(biāo)簽屬性,所以 thymeleaf 的模板可以靜態(tài)地運(yùn)行;當(dāng)有數(shù)據(jù)返回到頁(yè)面時(shí),Thymeleaf 標(biāo)簽會(huì)動(dòng)態(tài)地替換掉靜態(tài)內(nèi)容,使頁(yè)面動(dòng)態(tài)顯示。所以它可以讓前端小姐姐在瀏覽器中查看頁(yè)面的靜態(tài)效果,又可以讓程序員小哥哥在服務(wù)端查看帶數(shù)據(jù)的動(dòng)態(tài)頁(yè)面效果。
- 開箱即用,為Spring提供方言,可直接套用模板實(shí)現(xiàn)JSTL、 OGNL表達(dá)式效果,避免每天因套用模板而修改JSTL、 OGNL標(biāo)簽的困擾。同時(shí)開發(fā)人員可以擴(kuò)展自定義的方言。
- SpringBoot官方推薦模板,提供了可選集成模塊(spring-boot-starter-thymeleaf),可以快速的實(shí)現(xiàn)表單綁定、屬性編輯器、國(guó)際化等功能。
Spring Boot整合Thymeleaf
題外話:在Spring Boot出現(xiàn)之前整合Thymeleaf你可能需要配置如下的Bean(采用Java Config)
@Bean
// 配置模板解析器
// Thymeleaf3使用ITemplateResolver接口,SpringResourceTemplateResolver實(shí)現(xiàn)類
// Thymeleaf3之前使用TemplateResolver接口,ServletContextTemplateResolver實(shí)現(xiàn)類
public ITemplateResolver templateResolver() {
SpringResourceTemplateResolver templateResolver =
new SpringResourceTemplateResolver();
templateResolver.setPrefix("/WEB-INF/templates/");
templateResolver.setSuffix(".html");
// 設(shè)置templateMode屬性為HTML5
templateResolver.setTemplateMode("HTML5");
// 設(shè)置編碼格式為UTF-8
templateResolver.setCharacterEncoding("UTF-8");
// templateResolver.setOrder(1);
// templateResolver.setCacheable(true);
return templateResolver;
}
@Bean
public TemplateEngine templateEngine(ITemplateResolver templateResolver) {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
// 注入模板解析器
templateEngine.setTemplateResolver(templateResolver);
return templateEngine;
}
@Bean
@Primary
public ViewResolver viewResolver(TemplateEngine templateEngine) {
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine);
return viewResolver;
}
得益于Spring Boot的自動(dòng)配置功能ThymeleafAutoConfiguration,Spring Boot整合Thymeleaf很便捷
添加依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
配置
application.yml
spring:
thymeleaf:
cache: false
encoding: UTF-8
mode: HTML5
prefix: classpath:/templates/
suffix: .html
servlet:
content-type: text/html
這里需要注意的是Spring Boot默認(rèn)情況下會(huì)緩存模板
spring.thymeleaf.cache=true,一般在開發(fā)時(shí)需要將此項(xiàng)設(shè)置為false,在部署時(shí)再將此值設(shè)置為true,以提高性能,但Spring Boot也提供了devtools開發(fā)者工具,默認(rèn)情況下devtools會(huì)禁用緩存選項(xiàng),因此使用devtools進(jìn)行熱部署便不用更改spring.thymeleaf.cache的默認(rèn)配置了,也不要在全局配置文件配置為true
關(guān)于devtools的使用可參考我的文章 SpringBoot學(xué)習(xí)筆記三:devtools與熱部署
這里貼出Spring Boot關(guān)于Thymeleaf的所有配置項(xiàng)(引自官方文檔)
# THYMELEAF
spring.thymeleaf.cache=true # Whether to enable template caching.
spring.thymeleaf.check-template=true # Whether to check that the template exists before rendering it.
spring.thymeleaf.check-template-location=true # Whether to check that the templates location exists.
spring.thymeleaf.enabled=true # Whether to enable Thymeleaf view resolution for Web frameworks.
spring.thymeleaf.enable-spring-el-compiler=false # Enable the SpringEL compiler in SpringEL expressions.
spring.thymeleaf.encoding=UTF-8 # Template files encoding.
spring.thymeleaf.excluded-view-names= # Comma-separated list of view names (patterns allowed) that should be excluded from resolution.
spring.thymeleaf.mode=HTML # Template mode to be applied to templates. See also Thymeleaf's TemplateMode enum.
spring.thymeleaf.prefix=classpath:/templates/ # Prefix that gets prepended to view names when building a URL.
spring.thymeleaf.reactive.chunked-mode-view-names= # Comma-separated list of view names (patterns allowed) that should be the only ones executed in CHUNKED mode when a max chunk size is set.
spring.thymeleaf.reactive.full-mode-view-names= # Comma-separated list of view names (patterns allowed) that should be executed in FULL mode even if a max chunk size is set.
spring.thymeleaf.reactive.max-chunk-size=0 # Maximum size of data buffers used for writing to the response, in bytes.
spring.thymeleaf.reactive.media-types= # Media types supported by the view technology.
spring.thymeleaf.servlet.content-type=text/html # Content-Type value written to HTTP responses.
spring.thymeleaf.suffix=.html # Suffix that gets appended to view names when building a URL.
spring.thymeleaf.template-resolver-order= # Order of the template resolver in the chain.
spring.thymeleaf.view-names= # Comma-separated list of view names (patterns allowed) that can be resolved.
Thymeleaf實(shí)踐
PageController
package com.example.springbootthymeleaf.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class PageController {
@GetMapping("/regist")
public String toRegistPage(Model model) {
model.addAttribute("title", "用戶注冊(cè)");
model.addAttribute("msg", "歡迎注冊(cè)");
return "regist";
}
}
src/main/resources/templates/regist.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title th:text="${title}">用戶注冊(cè)</title>
<link rel="stylesheet" >
<script src="http://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<form class="col-md-4 col-md-offset-4" th:action="@{/regist}"
method="post">
<fieldset>
<legend th:text="${msg}">歡迎注冊(cè)</legend>
<div class="input-group form-group">
<span class="input-group-addon glyphicon glyphicon-user"></span>
<input id="username" name="username" class="form-control"
placeholder="請(qǐng)輸入用戶名"/>
</div>
<div class="input-group form-group">
<span class="input-group-addon glyphicon glyphicon-lock"></span>
<input type="password" id="password" name="password" class="form-control"
placeholder="請(qǐng)輸入密碼"/>
</div>
<div class="input-group form-group">
<span class="input-group-addon glyphicon glyphicon-envelope"></span>
<input id="email" name="email" class="form-control"
placeholder="請(qǐng)輸入郵箱賬號(hào)"/>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-3">
<button type="reset" class="btn btn-default btn-primary">重置</button>
<button type="submit" class="btn btn-default btn-primary">注冊(cè)</button>
</div>
</div>
</fieldset>
</form>
</div>
</div>
</body>
</html>
靜態(tài)效果
在系統(tǒng)資源管理器找到regist.html雙擊即可打開

動(dòng)態(tài)效果
啟動(dòng)工程訪問(wèn)http://localhost:8080/regist

Thymeleaf語(yǔ)法可參考