Thymeleaf——先导篇

1,002 阅读3分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

本文系作者 不太自律的程序猿原创,转载请私信并在文章开头附带作者和原文地址链接。

唠家常

本文是Thymeleaf系列中的先导篇,会对Thymeleaf做一些介绍,后续会持续更新在学习使用Thymeleaf过程中遇到的问题以及解决方案。

话不多说,直接开整!

下面是一些Thymeleaf官网的网站,自由观看。

Thymeleaf介绍

引用官网的介绍

Thymeleaf is a modern server-side Java template engine for both web and standalone environments.

Thymeleaf's main goal is to bring elegant natural templates to your development workflow — HTML that can be correctly displayed in browsers and also work as static prototypes, allowing for stronger collaboration in development teams.

With modules for Spring Framework, a host of integrations with your favourite tools, and the ability to plug in your own functionality, Thymeleaf is ideal for modern-day HTML5 JVM web development — although there is much more it can do.

翻译后为:

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

Thymeleaf 的主要目标是为您的开发工作流程带来优雅的自然模板——HTML可以在浏览器中正确显示,也可以作为静态原型工作,从而加强开发团队的协作。

凭借 Spring Framework 的模块、与您最喜欢的工具的大量集成以及插入您自己的功能的能力,Thymeleaf 是现代 HTML5 JVM Web 开发的理想选择——尽管它还有更多功能。

这个时候就出现一个问题了,我们为什么要使用Thymeleaf?

如果希望以 Jar 形式发布模块则尽量不要使用 JSP 相关知识,这是因为 JSP 在内嵌的 Servlet 容器上运行有一些问题 (内嵌 Tomcat、 Jetty 不支持 Jar 形式运行 JSP,Undertow 不支持 JSP)。
Spring Boot 中推荐使用 Thymeleaf 作为模板引擎,因为 Thymeleaf 提供了完美的 Spring MVC 支持。同时Spring Boot 提供了大量模板引擎,包括:

  • FreeMarker
  • Groovy
  • Mustache
  • Thymeleaf
  • Velocity
  • Beetl

官方对于Thymeleaf 可以完全替代 JSP 和 JSTL 吗? 这个问题给出的回复是绝对可以的,并且强烈推荐这么做。并且也给出了一篇文章,对这两种技术进行了比较,Thymeleaf 与 JSP,感兴趣的小伙伴可以自行查看。

SpringBoot集成Thymeleaf

maven依赖

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

两种配置方式,一种是properties方式,一种是yml,自行选择一种

  1. application.properties
# 开发阶段,建议关闭thymeleaf的缓存
spring.thymeleaf.cache=false
#使用遗留的html5以去掉对html标签的校验
spring.thymeleaf.mode=LEGACYHTML5
  1. application.yml
spring:
  thymeleaf:
    cache: false
    mode: LEGACYHTML5

IndexController

@Controller
@RequestMapping("/index")
public class IndexController {

    @RequestMapping("/home")
    public String hello(Model model) {
        model.addAttribute("msg", "不太自律的程序猿");
        return "test";
    }
    
}

在 src/main/resources/templates 下面创建 模板文件 home.html
文件路径: image.png home.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>不太自律的程序猿</title>
</head>
<body>
    <span th:text="${msg}">springboot集成thymeleaf</span>
</body>
</html>

启动程序,访问http://localhost:8080/index/home 即可。

后续会持续更新,感兴趣的小伙伴可以持续关注!

感谢诸君的观看,文中如有纰漏,欢迎在评论区来交流。如果这篇文章帮助到了你,欢迎点赞👍关注。