一、添加起步依赖:html
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
二、添加配置(application.properties):java
#开发时关闭缓存,否则无法看到实时页面 spring.thymeleaf.cache=false
参考ThymeleafProperties.java类,cache默认为true,其它属性都有默认值,通常不须要修改。web
三、写测试controller返回页面并携带数据:spring
package cn.mmweikt.es.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; @Controller public class IndexController { @GetMapping("/index") public String indexPage(Model model) { model.addAttribute("name", "es_project."); return "index"; } }
四、在resources/templates下放.html页面,在resources/static下放静态文件。templates和static下均可以再放文件夹:缓存
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <span th:text="${name}"></span> </body> </html>
注意,在html标签里必定要引入 xmlns:th="http://www.thymeleaf.org" ,这样thymeleaf模板才会启用,才能使用th:*这样的语法。
语法可参考:
https://www.cnblogs.com/jin-zhe/p/8202885.html
https://www.cnblogs.com/nfcm/p/7843935.htmlapp
补充:
网上看到说,在spring-boot1.4以后,支持thymeleaf3,能够更改版本号来进行修改支持。3相比2极大的提升了效率,而且不须要标签闭合,相似的link,img等都有了很好的支持,按照以下配置便可:spring-boot
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <!-- set thymeleaf version --> <thymeleaf.version>3.0.0.RELEASE</thymeleaf.version> <thymeleaf-layout-dialect.version>2.0.0</thymeleaf-layout-dialect.version> <!--set java version--> <java.version>1.8</java.version> </properties>