Template Engines for Spring – Spring的模板引擎

最后修改: 2017年 8月 2日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

The Spring web framework is built around the MVC (Model-View-Controller) pattern, which makes it easier to separate concerns in an application. This allows for the possibility to use different view technologies, from the well established JSP technology to a variety of template engines.

Spring Web框架是围绕MVC(模型-视图-控制器)模式建立的,这使得在一个应用程序中分离关注点变得更加容易。这使得使用不同的视图技术成为可能,从成熟的JSP技术到各种模板引擎。

In this article, we’re going to take a look at the main template engines that can be used with Spring, their configuration, and examples of use.

在这篇文章中,我们将看看可以与Spring一起使用的主要模板引擎、它们的配置和使用实例。

2. Spring View Technologies

2.春景科技

Given that concerns in a Spring MVC application are cleanly separated switching from one view technology to another is primarily a matter of configuration.

鉴于Spring MVC应用中的关注点是干净地分离的,从一种视图技术切换到另一种技术主要是配置问题。

To render each view type, we need to define a ViewResolver bean corresponding to each technology. This means that we can then return the view names from @Controller mapping methods in the same way we usually return JSP files.

为了渲染每个视图类型,我们需要定义一个ViewResolverbean,与每个技术相对应。这意味着我们可以从@Controller映射方法中返回视图名称,就像我们通常返回JSP文件一样。

In the following sections, we’re going to go over more traditional technologies like Java Server Pages, as well as the main template engines that can be used with Spring: Thymeleaf, Groovy, FreeMarker, Jade.

在下面的章节中,我们将介绍更多的传统技术,如Java Server Pages,以及可用于Spring的主要模板引擎。ThymeleafGroovyFreeMarker、Jade。

For each of these, we will go over the configuration necessary both in a standard Spring application and an application built using Spring Boot.

对于其中的每一项,我们将讨论标准Spring应用程序和使用Spring Boot构建的应用程序中的必要配置。

3. Java Server Pages

3.Java服务器页面

JSP is one of the most popular view technologies for Java applications, and it is supported by Spring out-of-the-box. For rendering JSP files, a commonly used type of ViewResolver bean is InternalResourceViewResolver:

JSP是Java应用程序中最流行的视图技术之一,Spring开箱即支持它。为了渲染JSP文件,一种常用的ViewResolverbean类型是InternalResourceViewResolver

@EnableWebMvc
@Configuration
public class ApplicationConfiguration implements WebMvcConfigurer {
    @Bean
    public ViewResolver jspViewResolver() {
        InternalResourceViewResolver bean = new InternalResourceViewResolver();
        bean.setPrefix("/WEB-INF/views/");
        bean.setSuffix(".jsp");
        return bean;
    }
}

Next, we can start creating JSP files in the /WEB-INF/views location:

接下来,我们可以开始在/WEB-INF/views位置创建JSP文件。

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
    <head>
        <meta http-equiv="Content-Type" 
          content="text/html; charset=ISO-8859-1">
        <title>User Registration</title>
    </head>
    <body>
        <form:form method="POST" modelAttribute="user">
            <form:label path="email">Email: </form:label>
            <form:input path="email" type="text"/>
            <form:label path="password">Password: </form:label>
            <form:input path="password" type="password" />
            <input type="submit" value="Submit" />
        </form:form>
    </body>
</html>

If we are adding the files to a Spring Boot application, then instead of in the ApplicationConfiguration class, we can define the following properties in an application.properties file:

如果我们将文件添加到Spring Boot应用程序中,那么我们可以在ApplicationConfiguration类中而不是在application.properties文件中定义以下属性。

spring.mvc.view.prefix: /WEB-INF/views/
spring.mvc.view.suffix: .jsp

Based on these properties, Spring Boot will auto-configure the necessary ViewResolver.

基于这些属性,Spring Boot将自动配置必要的ViewResolver

4. Thymeleaf

4.Thymeleaf

Thymeleaf is a Java template engine which can process HTML, XML, text, JavaScript or CSS files. Unlike other template engines, Thymeleaf allows using templates as prototypes, meaning they can be viewed as static files.

Thymeleaf是一个Java模板引擎,可以处理HTML、XML、文本、JavaScript或CSS文件。与其他模板引擎不同,Thymeleaf允许将模板作为原型使用,这意味着它们可以被视为静态文件。

4.1. Maven Dependencies

4.1.Maven的依赖性

To integrate Thymeleaf with Spring, we need to add the thymeleaf and thymeleaf-spring4 dependencies:

为了将Thymeleaf与Spring集成,我们需要添加thymeleafthymeleaf-spring4依赖项。

<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf</artifactId>
    <version>3.0.11.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring5</artifactId>
    <version>3.0.11.RELEASE</version>
</dependency>

If we have a Spring 4 project, then we need to add thymeleaf-spring4.

如果我们有一个Spring 4项目,那么我们需要添加thymeleaf-spring4

4.2. Spring Configuration

4.2.Spring配置

Next, we need to add the configuration which requires a SpringTemplateEngine bean, as well as a TemplateResolver bean that specifies the location and type of the view files.

接下来,我们需要添加配置,这需要一个SpringTemplateEngine bean,以及一个TemplateResolver bean,指定视图文件的位置和类型。

The SpringResourceTemplateResolver is integrated with Spring’s resource resolution mechanism:

SpringResourceTemplateResolver与Spring的资源解析机制集成。

@Configuration
@EnableWebMvc
public class ThymeleafConfiguration {
 
    @Bean
    public SpringTemplateEngine templateEngine() {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(thymeleafTemplateResolver());
        return templateEngine;
    }

    @Bean
    public SpringResourceTemplateResolver thymeleafTemplateResolver() {
        SpringResourceTemplateResolver templateResolver 
          = new SpringResourceTemplateResolver();
        templateResolver.setPrefix("/WEB-INF/views/");
        templateResolver.setSuffix(".html");
        templateResolver.setTemplateMode("HTML5");
        return templateResolver;
    }
}

Also, we need a ViewResolver bean of type ThymeleafViewResolver:

另外,我们需要一个ViewResolver类型的ThymeleafViewResolverbean。

@Bean
public ThymeleafViewResolver thymeleafViewResolver() {
    ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
    viewResolver.setTemplateEngine(templateEngine());
    return viewResolver;
}

4.3. Thymeleaf Templates

4.3.Thymeleaf模板

Now we can add an HTML file in the WEB-INF/views location:

现在我们可以在WEB-INF/views位置添加一个HTML文件。

<html>
    <head>
        <meta charset="ISO-8859-1" />
        <title>User Registration</title>
    </head>
    <body>
        <form action="#" th:action="@{/register}" 
          th:object="${user}" method="post">
            Email:<input type="text" th:field="*{email}" />
            Password:<input type="password" th:field="*{password}" />
            <input type="submit" value="Submit" />
        </form>
    </body>
</html>

Thymeleaf templates are very similar in syntax to HTML templates.

Thymeleaf模板的语法与HTML模板非常相似。

Some of the features that are available when using Thymeleaf in a Spring application are:

在Spring应用程序中使用Thymeleaf时,有一些功能是可用的。

    • support for defining forms behavior
    • binding form inputs to data models
    • validation for form inputs
    • displaying values from message sources
    • rendering template fragments

You can read more about using Thymeleaf templates in our article Thymeleaf in Spring MVC.

您可以在我们的文章Spring MVC中的Thymeleaf中阅读更多关于使用Thymeleaf模板的信息。

4.4. Thymeleaf in Spring Boot

4.4.ThymeleafSpring Boot中的应用

Spring Boot will provide auto-configuration for Thymeleaf by adding the spring-boot-starter-thymeleaf dependency:

Spring Boot将通过添加spring-boot-starter-thymeleaf依赖项,为Thymeleaf提供自动配置。

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

No explicit configuration is necessary. By default, HTML files should be placed in the resources/templates location.

没有必要进行明确的配置。默认情况下,HTML文件应该被放在resources/templates位置。

5. FreeMarker

5.FreeMarker

FreeMarker is a Java-based template engine built by the Apache Software Foundation. It can be used to generate web pages, but also source code, XML files, configuration files, emails and other text-based formats.

FreeMarker是一个基于Java的模板引擎,由Apache软件基金会构建。它可以用来生成网页,也可以生成源代码、XML文件、配置文件、电子邮件和其他基于文本的格式。

The generation is done based on template files written using the FreeMarker Template Language.

生成是基于使用FreeMarker Template Language编写的模板文件。

5.1. Maven Dependencies

5.1.Maven的依赖性

To start using the templates in our project, we need the freemarker dependency:

为了在我们的项目中开始使用模板,我们需要freemarker依赖。

<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.23</version>
</dependency>

For Spring integration, we also need the spring-context-support dependency:

对于Spring集成,我们还需要spring-context-support依赖。

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>5.2.8.RELEASE</version>
</dependency>

5.2. Spring Configuration

5.2.Spring配置

Integrating FreeMarker with Spring MVC requires defining a FreemarkerConfigurer bean which specifies the location of the template files:

FreeMarker与Spring MVC集成需要定义一个FreemarkerConfigurer Bean,它指定了模板文件的位置。

@Configuration
@EnableWebMvc
public class FreemarkerConfiguration {
 
    @Bean 
    public FreeMarkerConfigurer freemarkerConfig() { 
        FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer(); 
        freeMarkerConfigurer.setTemplateLoaderPath("/WEB-INF/views/");
        return freeMarkerConfigurer; 
    }
}

Next, we need to define an appropriate ViewResolver bean of type FreeMarkerViewResolver:

接下来,我们需要定义一个适当的ViewResolverbean,类型为FreeMarkerViewResolver

@Bean 
public FreeMarkerViewResolver freemarkerViewResolver() { 
    FreeMarkerViewResolver resolver = new FreeMarkerViewResolver(); 
    resolver.setCache(true); 
    resolver.setPrefix(""); 
    resolver.setSuffix(".ftl"); 
    return resolver; 
}

5.3. FreeMarker Templates

5.3.FreeMarker模板

We can create an HTML template using FreeMarker in the WEB-INF/views location:

我们可以使用FreeMarkerWEB-INF/views位置创建一个HTML模板。

<#import "/spring.ftl" as spring/>
<html>
    <head>
        <meta charset="ISO-8859-1" />
        <title>User Registration</title>
    </head>
    <body>
        <form action="register" method="post">
            <@spring.bind path="user" />
            Email: <@spring.formInput "user.email"/>
            Password: <@spring.formPasswordInput "user.password"/>
            <input type="submit" value="Submit" />
        </form>
    </body>
</html>

In the example above, we have imported a set of macros defined by Spring for working with forms in FreeMarker, including binding form inputs to data models.

在上面的例子中,我们导入了一组由Spring定义的宏,用于在FreeMarker中处理表单,包括将表单输入绑定到数据模型。

Also, the FreeMarker Template Language contains a large number of tags, directives, and expressions for working with collections, flow control structures, logical operators, formatting and parsing strings, numbers and many more features.

另外,FreeMarker模板语言包含大量的标签、指令和表达式,用于处理集合、流控制结构、逻辑运算符、格式化和解析字符串、数字和更多的功能。

5.4. FreeMarker in Spring Boot

5.4.FreeMarkerSpring Boot中的应用

In a Spring Boot application, we can simplify the needed configuration by using the spring-boot-starter-freemarker dependency:

Spring Boot应用程序中,我们可以通过使用spring-boot-starter-freemarker依赖来简化所需的配置。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
    <version>2.5.6</version>
</dependency>

This starter adds the necessary auto-configuration. All we need to do is start placing our template files in the resources/templates folder.

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

6. Groovy

6.Groovy

Spring MVC views can also be generated using the Groovy Markup Template Engine. This engine is based on a builder syntax and can be used for generating any text format.

Spring MVC视图也可以使用Groovy Markup Template Engine生成。该引擎基于构建器语法,可用于生成任何文本格式。

6.1. Maven Dependencies

6.1.Maven的依赖性

The groovy-templates dependency needs to be added to our pom.xml:

groovy-templates依赖性需要被添加到我们的pom.xml

<dependency>
    <groupId>org.codehaus.groovy</groupId>
    <artifactId>groovy-templates</artifactId>
    <version>2.4.12</version>
</dependency>

6.2. Spring Configuration

6.2.Spring配置

The integration of the Markup Template Engine with Spring MVC requires defining a GroovyMarkupConfigurer bean and a ViewResolver of type GroovyMarkupViewResolver:

Markup模板引擎与Spring MVC集成需要定义一个GroovyMarkupConfigurer Bean和一个GroovyMarkupViewResolver类型的ViewResolver

@Configuration
@EnableWebMvc
public class GroovyConfiguration {
 
    @Bean
    public GroovyMarkupConfigurer groovyMarkupConfigurer() {
        GroovyMarkupConfigurer configurer = new GroovyMarkupConfigurer();
        configurer.setResourceLoaderPath("/WEB-INF/views/");
        return configurer;
    }
    
    @Bean
    public GroovyMarkupViewResolver thymeleafViewResolver() {
        GroovyMarkupViewResolver viewResolver = new GroovyMarkupViewResolver();
        viewResolver.setSuffix(".tpl");
        return viewResolver;
    }
}

6.3. Groovy Markup Templates

6.3. Groovy Markup模板

Templates are written in the Groovy language and have several characteristics:

模板是用Groovy语言编写的,有几个特点。

    • they are compiled into bytecode
    • they contain support for fragments and layouts
    • they provide support for internationalization
    • the rendering is fast

Let’s create a Groovy template for our “User Registration” form, which includes data bindings:

让我们为我们的 “用户注册 “表单创建一个Groovy模板,它包括数据绑定。

yieldUnescaped '<!DOCTYPE html>'                                                    
html(lang:'en') {                                                                   
    head {                                                                          
        meta('http-equiv':'"Content-Type" ' +
          'content="text/html; charset=utf-8"')      
        title('User Registration')                                                            
    }                                                                               
    body {                                                                          
        form (id:'userForm', action:'register', method:'post') {
            label (for:'email', 'Email')
            input (name:'email', type:'text', value:user.email?:'')
            label (for:'password', 'Password')
            input (name:'password', type:'password', value:user.password?:'')
            div (class:'form-actions') {
                input (type:'submit', value:'Submit')
            }                             
        }
    }                                                                               
}

6.4. Groovy Template Engine in Spring Boot

6.4.Groovy模板引擎Spring Boot中的应用

Spring Boot contains auto-configuration for the Groovy Template Engine, which is added by including the spring-boot-starter-groovy-templates dependency:

Spring Boot包含Groovy Template Engine的自动配置,它是通过包括spring-boot-starter-groovy-templates依赖项来添加的。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-groovy-templates</artifactId>
    <version>2.5.6</version>
</dependency>

The default location for the templates is /resources/templates.

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

7. Jade4j

7.Jade4j

Jade4j is the Java implementation of the Pug template engine (originally known as Jade) for Javascript. Jade4j templates can be used for generating HTML files.

Jade4jPug模板引擎(最初称为Jade)的Java实现。Jade4j模板可用于生成HTML文件。

7.1. Maven Dependencies

7.1.Maven的依赖性

For Spring integration, we need the spring-jade4j dependency:

对于Spring集成,我们需要spring-jade4j依赖。

<dependency>
    <groupId>de.neuland-bfi</groupId>
    <artifactId>spring-jade4j</artifactId>
    <version>1.2.5</version>
</dependency>

7.2. Spring Configuration

7.2.Spring配置

To use Jade4j with Spring, we have to define a SpringTemplateLoader bean that configures the location of the templates, as well as a JadeConfiguration bean:

为了在Spring中使用Jade4j,我们必须定义一个SpringTemplateLoader Bean,以配置模板的位置,以及一个JadeConfiguration Bean。

@Configuration
@EnableWebMvc
public class JadeTemplateConfiguration {
 
    @Bean
    public SpringTemplateLoader templateLoader() {
        SpringTemplateLoader templateLoader 
          = new SpringTemplateLoader();
        templateLoader.setBasePath("/WEB-INF/views/");
        templateLoader.setSuffix(".jade");
        return templateLoader;
    }
 
    @Bean
    public JadeConfiguration jadeConfiguration() {
        JadeConfiguration configuration 
          = new JadeConfiguration();
        configuration.setCaching(false);
        configuration.setTemplateLoader(templateLoader());
        return configuration;
    }
}

Next, we need the usual ViewResolver bean, in this case of type JadeViewResolver:

接下来,我们需要通常的ViewResolver bean,在这种情况下是JadeViewResolver类型。

@Bean
public ViewResolver viewResolver() {
    JadeViewResolver viewResolver = new JadeViewResolver();
    viewResolver.setConfiguration(jadeConfiguration());
    return viewResolver;
}

7.3. Jade4j Templates

7.3.Jade4j模板

Jade4j templates are characterized by an easy-to-use whitespace-sensitive syntax:

Jade4j模板的特点是易于使用的白空间敏感语法。

doctype html
html
  head
    title User Registration
  body
    form(action="register" method="post" )
      label(for="email") Email:
      input(type="text" name="email")
      label(for="password") Password:
      input(type="password" name="password")
      input(type="submit" value="Submit")

The project also provides a very useful interactive documentation, where you can view the output of your template as you write it.

该项目还提供了一个非常有用的交互式文档,您可以在编写模板时查看其输出。

Spring Boot does not provide a Jade4j starter, so in a Boot project, we would have to add the same Spring configuration as defined above.

Spring Boot不提供Jade4j启动器,所以在Boot项目中,我们必须添加与上面定义的Spring配置。

8. Other Template Engines

8.其他模板引擎

Besides the template engines described so far, there are quite a few more available which may be used.

除了到目前为止所描述的模板引擎外,还有不少可供使用的模板。

Let’s review some of them briefly.

让我们简单回顾一下其中一些。

Velocity is an older template engine, which is very complex but has the disadvantage that Spring has deprecated its use since version 4.3 and removed completely in Spring 5.0.1.

Velocity是一个较早的模板引擎,它非常复杂,但缺点是Spring从4.3版本开始就不再使用它,并在Spring 5.0.1中完全删除。

JMustache is a template engine which can be easily integrated into a Spring Boot application by using the spring-boot-starter-mustache dependency.

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

Pebble contains support for Spring and Spring Boot within its libraries.

Pebble在其库中包含了对Spring和Spring Boot的支持。

Other templating libraries such as Handlebars or React, running on top of a JSR-223 script engine such as Nashorn, can also be used.

其他模板库,如HandlebarsReact,在JSR-223脚本引擎(如Nashorn)之上运行,也可以使用。

9. Conclusion

9.结论

In this article, we have gone over some of the most popular template engines for Spring web applications.

在这篇文章中,我们已经介绍了一些最流行的Spring Web应用程序的模板引擎。

And, as always, the full source code of the examples can be found over on GitHub.

而且,像往常一样,这些例子的完整源代码可以在GitHub上找到