Springboot学习笔记8:Thymeleaf 模板引擎

Posted Vincent9847

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Springboot学习笔记8:Thymeleaf 模板引擎相关的知识,希望对你有一定的参考价值。

一、Thymeleaf模板引擎是什么?

Thymeleaf是一个现代服务器端Java模板引擎,适用于Web和独立环境,能够处理html,XML,javascript,CSS甚至纯文本。

为什么要使用Thymeleaf?

  • Spring 官方放弃 JSP 是暂时没有好的解决方案,因为 JSP 需要本地空间保存 JSP 引擎动态生成的 Servlet 类,而 Spring Boot 程序往往是以 Jar 的形式脱离容器独立运行,这就需要设置额外的地址去保存,会有安全上的问题,背离了 Spring Boot 最初设计的目的。
  • Thymeleaf 的生产力比较好。它的标签比较简单,最大的优点,它允许前端人员即时查看静态页面的效果,这是 FreeMaker 或者 Velocity 等其它模板做不到的功能。考虑到横向添加 SSR 服务很方便,所以效率并不是什么大问题。

二、配置Thymeleaf

1.导入依赖

<!--thymeleaf-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2.Thymeleaf 的自动配置类 ThymeleafProperties

@ConfigurationProperties(
    prefix = "spring.thymeleaf"
)
public class ThymeleafProperties {
    private static final Charset DEFAULT_ENCODING;
    public static final String DEFAULT_PREFIX = "classpath:/templates/";
    public static final String DEFAULT_SUFFIX = ".html";
    private boolean checkTemplate = true;
    private boolean checkTemplateLocation = true;
    private String prefix = "classpath:/templates/";
    private String suffix = ".html";
    private String mode = "HTML";
    private Charset encoding;
}

html页面放在类路径下的templates下,thymeleaf就可以帮我们自动渲染。

三、测试

1.编写 TestController

@RequestMapping("/t1")
public String test1(Model model){
    //存入数据
    model.addAttribute("msg","Hello,Thymeleaf");
    //classpath:/templates/test.html
    return "test";
}

2.编写 html 

需要导入命名空间的约束:

xmlns:th="http://www.thymeleaf.org"

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>test</title>
</head>
<body>
<h1>测试页面</h1>

<!--th:text就是将div中的内容设置为它指定的值,和之前学习的Vue一样-->
<div th:text="${msg}"></div>
</body>
</html>

3.结果

*四、基本语法 

以上是关于Springboot学习笔记8:Thymeleaf 模板引擎的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot学习笔记:整合Thymeleaf

Spring boot 学习笔记

thymeleaf学习笔记

Spring Boot 学习笔记--整合Thymeleaf

SpringBoot笔记(五)模板引擎thymeleaf和freemarker

spring boot 学习笔记