Spring MVC + Thymeleaf 3.0: New Features – Spring MVC + Thymeleaf 3.0:新功能

最后修改: 2016年 10月 3日

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

1. Introduction

1.介绍

Thymeleaf is a Java template engine for processing and creating HTML, XML, JavaScript, CSS and plain text. For an intro to Thymeleaf and Spring, have a look at this write-up.

Thymeleaf是一个Java模板引擎,用于处理和创建HTML、XML、JavaScript、CSS和纯文本。关于Thymeleaf和Spring的介绍,请看本篇文章

In this article, we will discuss new features of Thymeleaf 3.0 in Spring MVC with Thymeleaf application. Version 3 comes with new features and many under-the-hood improvements. To be more specific, we will cover the topics of natural processing and Javascript inlining.

在这篇文章中,我们将讨论Thymeleaf 3.0的新功能在Spring MVC中的Thymeleaf应用。第3版包含了新的功能和许多内在的改进。更具体地说,我们将讨论自然处理和Javascript内联等话题。

Thymeleaf 3.0 includes three new textual template modes: TEXT, JAVASCRIPT, and CSS – which are meant to be used for processing plain, JavaScript and CSS templates, respectively.

Thymeleaf 3.0包括三种新的文本模板模式。TEXTJAVASCRIPTCSS–它们分别用于处理普通、JavaScript和CSS模板。

2. Maven Dependencies

2.Maven的依赖性

First, let us see the configurations required to integrate Thymeleaf with Spring; thymeleaf-spring library is required in our dependencies:

首先,让我们看看整合Thymeleaf和Spring所需的配置;thymeleaf-spring库在我们的依赖中是必需的。

<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>

Note that, for a Spring 4 project, the thymeleaf-spring4 library must be used instead of thymeleaf-spring5. The latest version of the dependencies can be found here.

请注意,对于Spring 4项目,必须使用thymeleaf-spring4库而不是thymeleaf-spring5。最新版本的依赖项可以在这里找到。

3. Java Thymeleaf Configuration

3.Java Thymeleaf配置

First, we need to configure new template engine, view and template resolvers. In order to do that, we need to update the Java config class, created

首先,我们需要配置新的模板引擎、视图和模板解析器。为了做到这一点,我们需要更新Java配置类,创建了

In order to do that, we need to update the Java config class, created here. In addition to new types of resolvers, our templates are implementing Spring interface ApplicationContextAware:

为了做到这一点,我们需要更新Java配置类,在这里创建。除了新类型的解析器外,我们的模板还实现了Spring接口ApplicationContextAware

@Configuration
@EnableWebMvc
@ComponentScan({ "com.baeldung.thymeleaf" })
public class WebMVCConfig implements WebMvcConfigurer, ApplicationContextAware {

    private ApplicationContext applicationContext;

    // Java setter

    @Bean
    public ViewResolver htmlViewResolver() {
        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
        resolver.setTemplateEngine(templateEngine(htmlTemplateResolver()));
        resolver.setContentType("text/html");
        resolver.setCharacterEncoding("UTF-8");
        resolver.setViewNames(ArrayUtil.array("*.html"));
        return resolver;
    }
    
    @Bean
    public ViewResolver javascriptViewResolver() {
        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
        resolver.setTemplateEngine(templateEngine(javascriptTemplateResolver()));
        resolver.setContentType("application/javascript");
        resolver.setCharacterEncoding("UTF-8");
        resolver.setViewNames(ArrayUtil.array("*.js"));
        return resolver;
    }
    
    @Bean
    public ViewResolver plainViewResolver() {
        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
        resolver.setTemplateEngine(templateEngine(plainTemplateResolver()));
        resolver.setContentType("text/plain");
        resolver.setCharacterEncoding("UTF-8");
        resolver.setViewNames(ArrayUtil.array("*.txt"));
        return resolver;
    }
}

As we may observe above, we created three different view resolvers – one for HTML views, one for Javascript files, and one for plain text files. Thymeleaf will differentiate them by checking filename extensions – .html, .js and .txt, respectively.

正如我们在上面看到的,我们创建了三个不同的视图解析器–一个用于HTML视图,一个用于Javascript文件,还有一个用于纯文本文件。Thymeleaf将通过检查文件名扩展名来区分它们–分别为.html.js.txt

We also created the static ArrayUtil class, in order to use method array() that creates required String[] array with view names.

我们还创建了静态的ArrayUtil类,以便使用array()方法,该方法用视图名称创建所需的String[]阵列。

In the next part of this class, we need to configure template engine:

在本课的下一部分,我们需要配置模板引擎。

private ISpringTemplateEngine templateEngine(ITemplateResolver templateResolver) {
    SpringTemplateEngine engine = new SpringTemplateEngine();
    engine.setTemplateResolver(templateResolver);
    return engine;
}

Finally, we need to create three separate template resolvers:

最后,我们需要创建三个独立的模板解析器。

private ITemplateResolver htmlTemplateResolver() {
    SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
    resolver.setApplicationContext(applicationContext);
    resolver.setPrefix("/WEB-INF/views/");
    resolver.setCacheable(false);
    resolver.setTemplateMode(TemplateMode.HTML);
    return resolver;
}
    
private ITemplateResolver javascriptTemplateResolver() {
    SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
    resolver.setApplicationContext(applicationContext);
    resolver.setPrefix("/WEB-INF/js/");
    resolver.setCacheable(false);
    resolver.setTemplateMode(TemplateMode.JAVASCRIPT);
    return resolver;
}
    
private ITemplateResolver plainTemplateResolver() {
    SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
    resolver.setApplicationContext(applicationContext);
    resolver.setPrefix("/WEB-INF/txt/");
    resolver.setCacheable(false);
    resolver.setTemplateMode(TemplateMode.TEXT);
    return resolver;
}

Please note, that for testing it is better to use non-cached templates, that’s why it is recommended to use setCacheable(false) method.

请注意,为了测试,最好使用非缓存的模板,这就是为什么建议使用setCacheable(false)方法。

Javascript templates will be stored in /WEB-INF/js/ folder, plain text files in /WEB-INF/txt/ folder, and finally path to HTML files is /WEB-INF/html.

Javascript模板将存储在/WEB-INF/js/文件夹中,纯文本文件存储在/WEB-INF/txt/文件夹中,最后,HTML文件的路径是/WEB-INF/html

4. Spring Controller Configuration

4.弹簧控制器配置

In order to test our new configuration, we created following Spring controller:

为了测试我们的新配置,我们创建了以下Spring控制器。

@Controller
public class InliningController {

    @RequestMapping(value = "/html", method = RequestMethod.GET)
    public String getExampleHTML(Model model) {
        model.addAttribute("title", "Baeldung");
        model.addAttribute("description", "<strong>Thymeleaf</strong> tutorial");
        return "inliningExample.html";
    }
    
    @RequestMapping(value = "/js", method = RequestMethod.GET)
    public String getExampleJS(Model model) {
        model.addAttribute("students", StudentUtils.buildStudents());
        return "studentCheck.js";
    }
    
    @RequestMapping(value = "/plain", method = RequestMethod.GET)
    public String getExamplePlain(Model model) {
        model.addAttribute("username", SecurityContextHolder.getContext()
          .getAuthentication().getName());
        model.addAttribute("students", StudentUtils.buildStudents());
        return "studentsList.txt";
    }
}

In the HTML file example, we’ll show how to use the new inlining feature, with and without escaping HTML tags.

在HTML文件的例子中,我们将展示如何使用新的内联功能,有无转义的HTML标签。

For the JS example we’ll generate an AJAX request, which will load js file with students information. Please note, that we are using simple buildStudents() method inside StudentUtils class, from this article.

对于JS的例子,我们将生成一个AJAX请求,它将加载包含学生信息的js文件。请注意,我们使用的是StudentUtils类中简单的buildStudents()方法,这个article

Finally, in the plaintext example, we’ll show student information as a text file. A typical example of using the plain text template mode could be used for sending plain-text email.

最后,在纯文本的例子中,我们将以文本文件的形式显示学生信息。使用纯文本模板模式的一个典型例子可用于发送纯文本电子邮件。

As an additional feature, we will use SecurityContextHolder, to obtain the logged username.

作为一个额外的功能,我们将使用SecurityContextHolder,以获得登录的用户名。

5. Html/Js/Text Example Files

5.Html/Js/Text 示例文件

The last part of this tutorial is to create three different types of files, and test the usage of the new Thymeleaf features. Let’s start with HTML file:

本教程的最后一部分是创建三种不同类型的文件,并测试Thymeleaf新功能的使用。让我们从HTML文件开始。

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Inlining example</title>
</head>
<body>
    <p>Title of tutorial: [[${title}]]</p>
    <p>Description: [(${description})]</p>
</body>
</html>

In this file we use two different approaches. In order to display title, we use escaped syntax, which will remove all HTML tags, resulting in displaying only text. In the case of description, we use unescaped syntax, to keep HTML tags. The final result will look like this:

在这个文件中,我们使用了两种不同的方法。为了显示标题,我们使用了转义语法,这将删除所有的HTML标签,导致只显示文本。在描述的情况下,我们使用非转义语法,以保留HTML标签。最后的结果将是这样的。

<p>Title of tutorial: Baeldung</p>
<p>Description: <strong>Thymeleaf</strong> tutorial</p>

which of course will be parsed by our browser, by displaying word Thymeleaf with a bold style.

这当然会被我们的浏览器解析,以粗体风格显示Thymeleaf一词。

Next, we proceed to test out js template features:

接下来,我们继续测试js模板的功能。

var count = [[${students.size()}]];
alert("Number of students in group: " + count);

Attributes in JAVASCRIPT template mode will be JavaScript-unescaped. It will result in creating js alert. We load this alert, by using jQuery AJAX, in the listStudents.html file:

JAVASCRIPT模板模式下的属性将是JavaScript-unescaped。这将导致创建js警报。我们通过使用jQuery AJAX,在listStudents.html文件中加载这个警报。

<script>
    $(document).ready(function() {
        $.ajax({
            url : "/spring-thymeleaf/js",
            });
        });
</script>

The last, but not the least function, that we want to test is plain text file generation. We created studentsList.txt file with following content:

最后,但不是最不重要的功能,我们要测试的是纯文本文件的生成。我们创建了studentsList.txt文件,内容如下。

Dear [(${username})],

This is the list of our students:
[# th:each="s : ${students}"]
   - [(${s.name})]. ID: [(${s.id})]
[/]
Thanks,
The Baeldung University

Note that, as with the markup template modes, the Standard Dialects include just one processable element ([# …]) and a set of processable attributes (th:text, th:utext, th:if, th:unless, th:each, etc.). The result will be a text file, that we may use for example in the email, as it was mentioned at the end of Section 3.

注意,和标记模板模式一样,标准方言只包括一个可处理的元素([# …])和一组可处理的属性(th:text, th:utext, th:if, th:unless, th:each,等等)。其结果将是一个文本文件,我们可以在电子邮件中使用,正如第3节末尾提到的那样。

How to test? Our suggestion is to play with the browser first, then check existing JUnit test as well.

如何测试?我们的建议是先玩玩浏览器,然后也检查现有的JUnit测试。

6. Thymeleaf in Spring Boot

6.Spring Boot中的Thymeleaf

Spring Boot provides 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.3.3.RELEASE</version>
</dependency>

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

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

7. Conclusion

7.结论

In this article, we discussed new features implemented in Thymeleaf framework with a focus on Version 3.0.

在这篇文章中,我们讨论了Thymeleaf框架中实现的新功能,重点是3.0版本。

The full implementation of this tutorial can be found in the GitHub project – this is an Eclipse based project, that is easy to test in every modern Internet browser.

本教程的完整实现可以在GitHub项目中找到 – 这是一个基于Eclipse的项目,可以在每个现代互联网浏览器中轻松测试。

Finally, if you’re planning to migrate a project from Version 2 to this latest version, have a look here at the migration guide. And note that your existing Thymeleaf templates are almost 100% compatible with Thymeleaf 3.0 so you will only have to do a few modifications in your configuration.

最后,如果您打算将一个项目从第2版迁移到这个最新版本,请看一下这里的迁移指南。请注意,您现有的Thymeleaf模板几乎100%与Thymeleaf 3.0兼容,因此您只需在配置中做一些修改即可。