Spring Boot模板引擎FreeMarker、Groovy、Thymeleaf、Mustache介绍

x33g5p2x  于2022-09-25 转载在 Spring  
字(2.3k)|赞(0)|评价(0)|浏览(1473)

这篇文章为您概述了 Spring Boot 支持的模板引擎。
Spring MVC 支持多种模板技术,包括 ThymeleafFreeMarker 和 JSP。此外,许多其他模板引擎包括他们自己的 Spring MVC 集成。
Spring Boot 包括对以下模板引擎的自动配置支持:

  1. FreeMarker
  2. Groovy
  3. Thymeleaf
  4. Mustache

让我们看一下上面每个模板引擎与spring boot的概述和用法。

1. FreeMarker

Apache FreeMarker 是一个模板引擎:一个基于模板和不断变化的数据生成文本输出(HTML 网页、电子邮件、配置文件、源代码等)的 Java 库。
Spring Boot 应用程序中,我们可以通过使用 spring-boot-starter-freemarker 依赖项来简化所需的配置:

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-freemarker -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
    <version>2.2.2.RELEASE</version>
</dependency>

此启动器添加了必要的自动配置。我们需要做的就是开始将我们的模板文件放在 resources/templates 文件夹中。

2. Groovy

此模板引擎基于构建器语法,可用于生成任何文本格式。 Spring Boot 包含 Groovy 模板引擎的自动配置,通过包含 spring-boot-starter-groovy-templates 依赖项添加:

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-groovy-templates -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-groovy-templates</artifactId>
    <version>2.2.2.RELEASE</version>
</dependency>

模板的默认位置是 /resources/templates。

3. Thymeleaf

它是一个模板引擎,能够处理和生成 HTML、XML、JavaScript、CSS、文本,并且可以在 Web 和非 Web 环境中工作。它更适合为 Web 应用程序的视图层提供服务,但它可以处理多种格式的文件,即使在离线环境中也是如此。
Spring Boot 将通过添加 *spring-boot-starter-thymeleaf *依赖项为 Thymeleaf 提供自动配置:

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
    <version>2.2.2.RELEASE</version>
</dependency>

Thymeleaf 与 Spring boot/Spring MVC 一起广泛用于开发基于 Spring 的 Web 应用程序。

4. Mustache

JMustache 是一个模板引擎,可以通过使用 spring-boot-starter-mustache 依赖项轻松集成到 Spring Boot 应用程序中。

Spring Boot 将通过添加 *spring-boot-starter-mustache *依赖项为 Mustache 提供自动配置:

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-mustache -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mustache</artifactId>
    <version>2.2.2.RELEASE</version>
</dependency>

当您将这些模板引擎之一与默认配置一起使用时,您的模板会自动从 src/main/resources/templates 中提取。

Spring boot 团队建议: 如果可能,应避免使用 JSP。将它们与嵌入式 servlet 容器一起使用时有几个已知的限制。

相关文章

微信公众号

最新文章

更多