16. SpringBoot 模板引擎 - Thymeleaf 基本使用

模板引擎类似于 JSP ,就是数据渲染显示那样的页面...

有很多种模板引擎,例举:

JSP、Velocity、Freemarker、Thymeleaf。。。

 

 

 

 

我们这用SpringBoot 推荐的 Thymeleaf; 功能强大又好用语法更简单。

 

我们引入thymeleaf的 GAV:

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

 

 

不用指定版本 看给你的是什么版本  ,自动下载配置,,,

如果你是2.X 版本的,那么你想用3版本以上等...就要指定替换: 【下面代码替换到pow properties 标签中】

<properties>
<thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
<!-- 布局功能的支持程序 thymeleaf3主程序 layout2以上版本 -->
<!--thymeleaf2 是配 layout1-->
<thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
</properties>

加入到 propertiess 标签里即可。

 

 

 现在肯定是最新版的,,,如果你是2版本,那么你想用3版本 Thymeleaf 视图要2版本以上,,,,因为2版本的Thymeleaf 对应的 视图版本是1  这里了解即可

推荐使用高版本  因为低版本很多无聊的一些限制。

 

如果你想更改 html 代码 然后不重启SpringBoot服务的话 那么推荐可以禁用掉模板引擎的缓存,IDEA中修改后你得重新编译 Ctrl + F9键 可实现:

 

 

 

Thymeleaf使用:

@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {
private static final Charset DEFAULT_ENCODING = Charset.forName("UTF‐8");
private static final MimeType DEFAULT_CONTENT_TYPE = MimeType.valueOf("text/html");
public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";
//

可以看到 意思是 在 类路径下面的 templates 以html 结尾的文件都一律解析。

 

所以我们试一下:

我们先写一个控制层 然后返回视图 ,SpringBoot 会在 里面找的了:【只要我们把HTML页面放在classpath:/templates/,thymeleaf就能自动渲染;】

package com.bihu.springboot.Control;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class ThymeleafTest {
    @RequestMapping("/ok")
    public String thymeleaf() {
        return "Thymeleaf";
    }
}
ThymeleafTest.java 【控制器】

 

 

 

 

 

 




 

<thymeleaf‐layout‐dialect.version>2.2.2</thymeleaf‐layout‐dialect.version>
posted @ 2021-08-07 14:32  咸瑜  阅读(136)  评论(0编辑  收藏  举报