thymeleaf介紹
Thymeleaf
是現代化服務器端的Java模板引擎,不同與其它幾種模板的是Thymeleaf
的語法更加接近HTML送淆,并且具有很高的擴展性税产。詳細資料可以瀏覽官網。
Thymeleaf特點
- 支持無網絡環(huán)境下運行偷崩,由于它支持 html 原型辟拷,然后在 html 標簽里增加額外的屬性來達到模板+數據的展示方式。瀏覽器解釋 html 時會忽略未定義的標簽屬性阐斜,所以 thymeleaf 的模板可以靜態(tài)地運行梧兼;當有數據返回到頁面時,Thymeleaf 標簽會動態(tài)地替換掉靜態(tài)內容智听,使頁面動態(tài)顯示羽杰。所以它可以讓前端小姐姐在瀏覽器中查看頁面的靜態(tài)效果,又可以讓程序員小哥哥在服務端查看帶數據的動態(tài)頁面效果到推。
- 開箱即用考赛,為Spring提供方言,可直接套用模板實現JSTL莉测、 OGNL表達式效果颜骤,避免每天因套用模板而修改JSTL、 OGNL標簽的困擾捣卤。同時開發(fā)人員可以擴展自定義的方言忍抽。
- SpringBoot官方推薦模板,提供了可選集成模塊(spring-boot-starter-thymeleaf)董朝,可以快速的實現表單綁定鸠项、屬性編輯器、國際化等功能子姜。
Spring Boot整合Thymeleaf
題外話:在Spring Boot
出現之前整合Thymeleaf
你可能需要配置如下的Bean
(采用Java Config
)
@Bean
// 配置模板解析器
// Thymeleaf3使用ITemplateResolver接口祟绊,SpringResourceTemplateResolver實現類
// Thymeleaf3之前使用TemplateResolver接口,ServletContextTemplateResolver實現類
public ITemplateResolver templateResolver() {
SpringResourceTemplateResolver templateResolver =
new SpringResourceTemplateResolver();
templateResolver.setPrefix("/WEB-INF/templates/");
templateResolver.setSuffix(".html");
// 設置templateMode屬性為HTML5
templateResolver.setTemplateMode("HTML5");
// 設置編碼格式為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
的自動配置功能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默認情況下會緩存模板
spring.thymeleaf.cache=true
牧抽,一般在開發(fā)時需要將此項設置為false
,在部署時再將此值設置為true
遥赚,以提高性能扬舒,但Spring Boot也提供了devtools開發(fā)者工具,默認情況下devtools會禁用緩存選項
凫佛,因此使用devtools進行熱部署便不用更改spring.thymeleaf.cache
的默認配置了讲坎,也不要在全局配置文件配置為true
關于devtools的使用可參考我的文章 SpringBoot學習筆記三:devtools與熱部署
這里貼出Spring Boot關于Thymeleaf的所有配置項(引自官方文檔)
# 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實踐
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", "用戶注冊");
model.addAttribute("msg", "歡迎注冊");
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}">用戶注冊</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}">歡迎注冊</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="請輸入用戶名"/>
</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="請輸入密碼"/>
</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="請輸入郵箱賬號"/>
</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">注冊</button>
</div>
</div>
</fieldset>
</form>
</div>
</div>
</body>
</html>
靜態(tài)效果
在系統(tǒng)資源管理器找到regist.html雙擊即可打開
動態(tài)效果
啟動工程訪問http://localhost:8080/regist
Thymeleaf語法可參考