讲解springboot中使用模板thymeleaf引擎

什么是thymeleaf

thymeleaf是一款用于渲染XML/XHTML/HTML5内容的模板引擎。类似JSP,Velocity,FreeMaker等,它也可以轻易的与Spring MVC等Web框架进行集成作为Web应用的模板引擎。与其它模板引擎相比,Thymeleaf最大的特点是能够直接在浏览器中打开并正确显示模板页面,而不需要启动整个Web应用,比如<span th:text="${name}">你好</span>这个标签,当直接打开静态页面的时候会显示你好,当使用动态数据之后会显示动态的数据,将你好覆盖

引入依赖

在springboot中使用thymeleaf,项目依赖web模块和thymeleaf

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
配置文件

springboot提供了Thymeleaf的默认配置,如果想要更改默认配置,需要在配置文件中修改相关属性

spring:
  thymeleaf:
    mode: HTML5
    servlet:
      content-type: text/html
    cache: false #是否开启缓存
    encoding: UTF-8 #编码
    prefix: classpath:/templates/ #模板路径
    suffix: .html # 后缀
模板

Spring Boot 官方推荐使用Thymeleaf模板引擎,默认的模板路径在src/main/resources/templates

新建一个test.html模板

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>测试</title>
</head>
<body>
<h4><span th:text="${name}">你好</span></h4>
我的博客地址是<span th:text="${url}"></span>
</body>
</html>

写个controller测试下

/**
 * @author: chenmingyu
 * @date: 2019/2/27 11:04
 * @description:
 */
@Controller
public class TestController {

    @GetMapping("test")
    public String test(Model model){

        model.addAttribute("name","叫我明羽");
        model.addAttribute("url","https://chenmingyu.top");
        return "test";
    }
}

访问 http://localhost:8080/test

想了解更多关于Thymeleaf的更多标签,语法可以访问Thymeleaf官网