Thymeleaf的学习(一)(定义及与springboot的整合)

Thymeleaf的定义和优点

 

Thymeleaf是跟Velocity、FreeMarker类似的模板引擎,它可以完全替代JSP,相较与其他的模板引擎,它主要有以下几个特点:

1. Thymeleaf在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以thymeleaf的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。

2. Thymeleaf开箱即用的特性。它提供标准和spring标准两种方言,可以直接套用模板实现JSTL、OGNL表达式效果,避免每天套模板、改jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。

3. Thymeleaf提供spring标准方言和一个与SpringMVC完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。

SpringBoot整合Thymeleaf

1. pom.xml中引入Thymeleaf的依赖 

<!--thymeleaf依赖-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--nekohtml意思是非严格html  引入这个依赖,并修改配置文件中spring.thymeleaf.mode=LEGACYHTML5,那么html中的标签就可以不用闭合了-->
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
    <artifactId>nekohtml</artifactId>
    <version>1.9.22</version>
</dependency>

2. application.properties中加入Thymeleaf的配置

#thymeleaf 
spring.thymeleaf.prefix=classpath:/templates/ 
spring.thymeleaf.check-template-location=true 
spring.thymeleaf.suffix=.html 
spring.thymeleaf.encoding=UTF-8 
spring.thymeleaf.content-type=text/html 
#关闭缓存,即时刷新,上线生产环境需要改为true
spring.thymeleaf.cache=false
#配置成html5,那么html页面的标签需要严格闭合
spring.thymeleaf.mode=HTML5
#配置成LEGACYHTML5,那么html页面的标签不用严格闭合
#spring.thymeleaf.mode=LEGACYHTML5

3. templates目录下创建一个html文件,这里比如为:thymeleaftest.html

注意:这里网上都说必须要在html标签里加上xmlns:th="http://www.thymeleaf.org",我没有加,发现也可以正常使用thymeleaf的方法,以后再观察。可以看出th:text这种写法就是thymeleaf的特点。

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>Title</title>
</head>
<body>
<h1 th:text="${name}"></h1>
</body>
</html>

4. 后台为:

//浏览器访问http://localhost:8080/fileoperate/thymeleaftest即可
@RequestMapping("/fileoperate")
public class fileOperateController {

    @RequestMapping("/thymeleaftest")
    public String thymeleaftest(Model model){
        model.addAttribute("name","张三");
        return "thymeleaftest";
    }

}

5. 效果为:

参考:

1. https://www.cnblogs.com/weknow619/p/8323497.html

持续更新!!!

原文地址:https://www.cnblogs.com/flyinghome/p/12487930.html