目录
1:什么是Thymeleaf模板引擎
2:springboot怎使用Thymeleaf
2.1:导入pom文件
2.2:查看ThymeleafAutoConfiguration
3:Thymeleaf核心语法
4:使用Thymeleaf
5:具体语法练习
1:什么是Thymeleaf模板引擎
在项目中,我们使用前后端分离或者前后端不分离的技术,如果不分离就需要引擎模板
引擎模板跟JSP相似,都是后端的模板解析器,将数据填充到模板页面,返回给前端的技术。
Thymeleaf是一个现代的服务器端Java模板引擎的web和独立的环境,能够处理HTML, XML, JavaScript, CSS,甚至纯文本。

2:springboot怎使用Thymeleaf
2.1:导入pom文件
<!-- 模板引擎 thymeleaf--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency>
2.2:查看ThymeleafAutoConfiguration
约定了配置规范和模板引擎的前缀、后缀
@AutoConfiguration(after = { WebMvcAutoConfiguration.class, WebFluxAutoConfiguration.class })
//模板配置 ThymeleafProperties
@EnableConfigurationProperties(ThymeleafProperties.class)
@ConditionalOnClass({ TemplateMode.class, SpringTemplateEngine.class })
@Import({ TemplateEngineConfigurations.ReactiveTemplateEngineConfiguration.class,TemplateEngineConfigurations.DefaultTemplateEngineConfiguration.class })
public class ThymeleafAutoConfiguration {//Spring资源模板解析器 这里配置了模板引擎@BeanSpringResourceTemplateResolver defaultTemplateResolver() {SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();resolver.setApplicationContext(this.applicationContext);//前缀resolver.setPrefix(this.properties.getPrefix());//后缀resolver.setSuffix(this.properties.getSuffix());//mode 是htmlresolver.setTemplateMode(this.properties.getMode());if (this.properties.getEncoding() != null) {resolver.setCharacterEncoding(this.properties.getEncoding().name());}resolver.setCacheable(this.properties.isCache());Integer order = this.properties.getTemplateResolverOrder();if (order != null) {resolver.setOrder(order);}resolver.setCheckExistence(this.properties.isCheckTemplate());return resolver;}}//查看模板配置文件@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;//前缀 约定了文件位置 在templates目录下public static final String DEFAULT_PREFIX = "classpath:/templates/";//后缀 约定了文件格式是 .htmlpublic static final String DEFAULT_SUFFIX = ".html";//省略了很多代码
}
3:Thymeleaf核心语法

4:使用Thymeleaf
1:编写controller
@Controller
public class Controller1 {@GetMapping(value = "well")public String hello(String name, Model model) {//前缀: classpath:/templates///后缀: .html//真实地址:classpath:/templates/Welcome.html//model模型存放参数 model就是Mapmodel.addAttribute("msg",name);return "Welcome";}
}
2:在templates下边编写Welcome.html
<!DOCTYPE html>
<!--引入命名空间 就有了提示-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
<h3>Welcome页面</h3>
<h5>你好呀, <span th:text="${msg}"></span>
</h5></body>
</html>
3:测试访问
http://localhost:8090/well?name=%E5%BC%A0%E4%B8%89

