Thymeleaf 是 Java 模板引擎,Spring 官方推荐使用,也是 Spring Boot 默认的模板引擎;前后端分离之前就是thymeleaf这类引擎模板的地盘;其支持HTML5的视图模板,能够无缝衔接springboot;主要用途能进行web开发和非web开发,比如页面渲染,代码生成,文档生成等等,做些日常的小工具是个很好的选择;
开发传统Java WEB工程时,我们可以使用JSP页面模板语言,但是在SpringBoot中已经不推荐使用了。SpringBoot支持如下页面模板语言
上面并没有列举所有SpringBoot支持的页面模板技术。其中Thymeleaf是SpringBoot官方所推荐使用的,下面来谈谈Thymeleaf一些常用的语法规则。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
Spring Boot默认存放模板页面的路径在
src/main/resources/templates
或者src/main/view/templates
,但是index.html默认是在static目录下。
这个无论是使用什么模板语言都一样,当然默认路径是可以自定义的,不过一般不推荐这样做。另外Thymeleaf默认的页面文件后缀是.html
。
application.properties添加配置项
#开启thymeleaf视图解析
spring.thymeleaf.enabled=true
#编码为UTF-8
spring.thymeleaf.encoding=UTF-8
#是否使用缓存(开发环境建议使用false,线上使用true)
spring.thymeleaf.cache=false
spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**
#严格执行HTML语法格式
spring.thymeleaf.mode=HTML
#模式
spring.thymeleaf.servlet.content-type=text/html
在templates目录下创建hello.html,内容
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>SpringBoot thymeleaf 模版渲染</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
</head>
<body>
<p th:text="'用户ID:' + ${pwd}"/>
<p th:text="'用户名称:' + ${name}"/>
</body>
</html>
controller
@Controller
@RequestMapping()
public class ThymeleafController {
@RequestMapping(value = "hello", method = RequestMethod.GET)
public String show(Model model){
model.addAttribute("pwd","123456");
model.addAttribute("name","Java后端技术全栈");
return "hello";
}
}
启动,访问http://localhost:8080/hello
OK,自此Spring Boot 集成Thymeleaf入门搞定。
如果想深入的了解Thmeleaf相关的,请关注官网
https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html
Thymeleaf的demo案例(集成Spring 、Spring Security 3.x and 4.x)
https://github.com/thymeleaf