SpringBoot2.1.5(33)---SpringBoot整合 Thymeleaf 模板引擎

 

目录

一、 Thymeleaf

简介:

Thymeleaf是用于Web和独立环境的现代服务器端Java模板引擎。

Thymeleaf的主要目标是将优雅的自然模板带到您的开发工作流程中—HTML能够在浏览器中正确显示,并且可以作为静态原型,从而在开发团队中实现更强大的协作。Thymeleaf能够处理HTML,XML,JavaScript,CSS甚至纯文本。

Thymeleaf的主要目标是提供一个优雅和高度可维护的创建模板的方式。 为了实现这一点,它建立在自然模板的概念之上,以不影响模板作为设计原型的方式将其逻辑注入到模板文件中。 这改善了设计沟通,弥合了前端设计和开发人员之间的理解偏差。

Thymeleaf也是从一开始就设计(特别是HTML5)允许创建完全验证的模板。

官网

https://www.thymeleaf.org/

官方文档

https://www.thymeleaf.org/documentation.html

入门资料参考:

https://blog.csdn.net/zrk1000/article/details/72667478

二、代码实践

1、maven依赖

        <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>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

2、yml 文件 配置

server:
  port: 8081
  
spring:
  application:
    name: thymeleaf

  thymeleaf:
    # 是否启用模板缓存。
    cache: true
    # 是否检查模板位置是否存在。
    check-template: true
    # 是否为Web框架启用Thymeleaf视图分辨率。
    enabled: true
    # 编码格式, 默认UTF-8
    encoding: UTF-8
    # 应用于模板的模板模式。另请参阅Thymeleaf的TemplateMode枚举。
    mode: HTML
    # 后缀 默认 .html
    suffix: .html
    # 模板文件存放位置  , 默认 classpath:/templates/
    prefix: classpath:/templates/

3、Thymeleaf 文件

创建 模板文件 index.html,文件内容如下

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

4、测试Controller

/**
 * created with IntelliJ IDEA.
 * author: fxbin
 * date: 2018/10/21
 * time: 4:42
 * version: 1.0
 * description:
 */
@Controller
public class ThymeleafController {

    @RequestMapping("/test")
    public String test(Model model){
        model.addAttribute("content", "Hello Thymeleaf");
        return "index";
    }
}

5、启动项目,进行测试

访问 http://localhost:8081/test , 可以看到我们设置在controller 中的内容成功显示在了页面上
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/zhangbijun1230/article/details/91357519