Spring Boot学习(七):Thymeleaf模板引擎在Spring Boot中的使用

这里是一个学习过程笔记的汇总:Spring Boot学习汇总


thymeleaf官网:https://www.thymeleaf.org/

1、什么是Thymeleaf?

        Thymeleaf是一款用于渲染XML/XHTML/HTML5内容的模板引擎。类似JSP,Velocity,FreeMaker等, 它也可以轻易的与Spring MVC等Web框架进行集成作为Web应用的模板引擎。与其它模板引擎相比, Thymeleaf最大的特点是能够直接在浏览器中打开并正确显示模板页面,而不需要启动整个Web应用。

2、怎么用?

在这里就介绍Spring Boot中使用Thymeleaf

        2.1、 导入thymeleaf模块相关的starter

<!-- thymeleaf模板引擎-->
<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

           导入这个starter之后,我们先看看这个tyymeleaf相关的自动配置。

所有的自动配置全到这个jar包下来找:

在autoconfigure中找到thymeleaf文件夹:

可以看到自动配置类:ThymeleafAutoConfiguration, 进入看:

之前就讲过这个自动配置原理,自动配置类都会有一个xxxProperties类,这里也不例外,有个ThymeleafProperties类,这个是开启自动配置文件,点进去看:

可以看到类注解@ConfigurationProperties后的prefix属性值,这个就是thymeleaf的自动配置文件,前面讲到过,这个配置文件和这个配置类一一对应,可以看到这个配置类有几个属性,前缀: "calsspath:/templates/"   后缀: ".html", 这个有点像SpringMVC中的视图解析器了哈。

这个就是说,只要我们在项目中将html页面放到calsspath:/templates/ 下,thymeleaf就能自动渲染,。

下面来写个简单的demo看一下。

2.2、thymeleaf相关demo

上面已经导入了thymeleaf相关的starter,下面创建一个controller,如下:

package com.xxx.demo.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author pavel
 * @date 2018/11/10
 */
@Controller
public class HelloController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @RequestMapping("/success")
    public String success(ModelMap modelMap) {
        String str = "hello, how are u?";
        modelMap.addAttribute("hello", str);
        return "success";
    }
}

我们给ModelMap绑定一个属性上,属性名为hello,属性值为字符串:hello, how aer u?

然后直接success字符串,thymeleaf就会自动加载calsspath:/templates/success.html

下面在templates文件夹下创建success.html,如下:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>SUCCESS</title>
</head>
<body>
    <div th:text="${hello}"></div>
</body>
</html>

导入thymeleaf的starter之后,穿件html时会在顶部自动加入thymeleaf的官网,这样我们在html里面写thymeleaf时会有语法提醒。如上,我们在div中加上了 th:text="${hello}", 这句的含义是,用这个值替换div的文本的值。

启动项目,然后访问success方法:

就会输出我们在hello上绑定的值:hello, how are u?

thymeleaf使用起来就是这么简单,模式都一样,后台传值, html页面利用thymeleaf语法进行展示。

那么最重要的还是thymeleaf语法了,关于语法,就不一一举例了,自己参考着官方文档撸一遍吧,说实话,我也就是大概看一下,有用到的时候再随查随用,毕竟语法太多,是记不下来的。

thymeleaf官方文档:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.pdf

这个是pdf格式,可以下载个pdf浏览工具,左侧会列出所有章节目录,看起来比较方便

好了 ,关于thymeleaf就说这么多吧。

发布了34 篇原创文章 · 获赞 43 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/pavel101/article/details/84028892