SpringBoot Thymeleaf模板引擎

作者:gqk


Thymeleaf概述

SpringBoot这个项目首先是以jar的方式,不是war,像第二,我们用的还是嵌入式的Tomcat,所以呢,他现在默认是不支持jsp的。

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

Thymeleaf使用

导入Thymeleaf的stater

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

 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;
    private boolean cache;
    private Integer templateResolverOrder;
    private String[] viewNames;
    private String[] excludedViewNames;
    private boolean enableSpringElCompiler;
    private boolean renderHiddenMarkersBeforeCheckboxes;
    private boolean enabled;
    private final ThymeleafProperties.Servlet servlet;
    private final ThymeleafProperties.Reactive reactive;
}

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

在templates文件下面编写test.html文件

注意在使用Thymeleaf模板引擎之前必须引入    xmlns:th="http://www.thymeleaf.org"

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>测试页面</h1>
    <div th:text="${msg}">我是测试页面</div>
</body>
</html>

 编写控制器接收请求

@Controller
public class TestController {
    @RequestMapping("/test")
    public String test(Model model){
        model.addAttribute("msg","hello Thymeleaf");
        return "test";
    }
}

 

访问:http://localhost:8080/test

 

 

 Thymeleaf语法很多见官方文档

https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#decoupled-logic-the-concept

 

posted @ 2021-02-25 10:17  少侠gqk  阅读(73)  评论(0编辑  收藏  举报