Spring Boot thymeleaf模板引擎的使用详解
在早期开发的时候,我们完成的都是静态页面也就是html页面,随着时间轴的发展,慢慢的引入了jsp页面,当在后端服务查询到数据之后可以转发到jsp页面,可以轻松的使用jsp页面来实现数据的显示及交互,jsp有非常强大的功能,但是,在使用springboot的时候,整个项目是以jar包的方式运行而不是war包,而且还嵌入了tomcat容器,因此,在默认情况下是不支持jsp页面的。如果直接以纯静态页面的方式会给我们的开发带来很大的麻烦,springboot推荐使用模板引擎。
模板引擎有很多种,jsp,freemarker,thymeleaf,模板引擎的作用就是我们来写一个页面模板,比如有些值呢,是动态的,我们写一些表达式。而这些值,从哪来呢,我们来组装一些数据,我们把这些数据找到。然后把这个模板和这个数据交给我们模板引擎,模板引擎按照我们这个数据帮你把这表达式解析、填充到我们指定的位置,然后把这个数据最终生成一个我们想要的内容给我们写出去,这就是我们这个模板引擎,不管是jsp还是其他模板引擎,都是这个思想。只不过不同的模板引擎语法不同而已,下面重点学习下springboot推荐使用的thymeleaf模板引擎,语法简单且功能强大
1、thymeleaf的介绍
官网地址:https://www.thymeleaf.org/
thymeleaf在github的地址:https://github.com/thymeleaf/thymeleaf
中文网站:https://raledong.gitbooks.io/using-thymeleaf/content/
导入依赖:
org.thymeleaf thymeleaf-spring5 org.thymeleaf.extras thymeleaf-extras-java8time 
在springboot中有专门的thymeleaf配置类:ThymeleafProperties
@ConfigurationProperties(prefix="spring.thymeleaf")
publicclassThymeleafProperties{
	privatestaticfinalCharsetDEFAULT_ENCODING=StandardCharsets.UTF_8;
	publicstaticfinalStringDEFAULT_PREFIX="classpath:/templates/";
	publicstaticfinalStringDEFAULT_SUFFIX=".html";
	/**
	*Whethertocheckthatthetemplateexistsbeforerenderingit.
	*/
	privatebooleancheckTemplate=true;
	/**
	*Whethertocheckthatthetemplateslocationexists.
	*/
	privatebooleancheckTemplateLocation=true;
	/**
	*PrefixthatgetsprependedtoviewnameswhenbuildingaURL.
	*/
	privateStringprefix=DEFAULT_PREFIX;
	/**
	*SuffixthatgetsappendedtoviewnameswhenbuildingaURL.
	*/
	privateStringsuffix=DEFAULT_SUFFIX;
	/**
	*Templatemodetobeappliedtotemplates.SeealsoThymeleaf'sTemplateModeenum.
	*/
	privateStringmode="HTML";
	/**
	*Templatefilesencoding.
	*/
	privateCharsetencoding=DEFAULT_ENCODING;
	/**
	*Whethertoenabletemplatecaching.
	*/
	privatebooleancache=true;
2、thymeleaf使用模板
在java代码中写入如下代码:
@RequestMapping("/hello")
publicStringhello(Modelmodel){
model.addAttribute("msg","Hello");
//classpath:/templates/hello.html
return"hello";
}
html页面中写入如下代码:
Hello
