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的介绍,请看本篇文章。
Besides these basic functions, Thymeleaf offers us a set of utility objects that will help us perform common tasks in our application.
除了这些基本功能,Thymeleaf还为我们提供了一组实用对象,它们将帮助我们在应用程序中执行常见的任务。
In this article, we’ll discuss a core feature in Thymeleaf 3.0 – Expression Utility Objects in Spring MVC applications. More specifically, we’ll cover the topic of processing dates, calendars, strings, objects and much more.
在这篇文章中,我们将讨论Thymeleaf 3.0的一个核心功能–Spring MVC应用程序中的表达式实用对象。更具体地说,我们将讨论处理日期、日历、字符串、对象等方面的话题。
2. Maven Dependencies
2.Maven的依赖性
First, let us see the required configuration needed to integrate Thymeleaf with Spring. The 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. Expression Utility Objects
3.表达式实用对象
Before looking at the core focus of this writeup, if you want to take a step back and see how to configure Thymeleaf 3.0 in your web app project, have a look at this tutorial.
在看这篇报道的核心重点之前,如果你想退一步看看如何在你的Web应用项目中配置Thymeleaf 3.0,可以看看这个教程。
For the purpose of the current article, we created a Spring controller and HTML file – to test out all the features we’re going to be discussing. Below is the complete list of available helper objects and their functions:
为了这篇文章的目的,我们创建了一个Spring控制器和HTML文件–来测试我们将要讨论的所有功能。下面是可用的辅助对象及其功能的完整列表。
- #dates: utility methods for java.util.Date objects
- #calendars: similar to #dates, used for java.util.Calendar objects
- #numbers: utility methods for formatting numeric objects
- #strings: utility methods for String objects
- #objects: utility methods for Java Object class in general
- #bools: utility methods for boolean evaluation
- #arrays: utility methods for arrays
- #lists: utility methods for lists
- #sets: utility methods for sets
- #maps: utility methods for maps
- #aggregates: utility methods for creating aggregates on arrays or collections
- #messages: utility methods for obtaining externalized messages inside variables expressions
3.1. Dates Objects
3.1. 日期对象
The first function that we want to discuss is processing of the java.util.Date objects. The expression utility objects responsible for date processing start with #dates.functionName(). The first function that we want to cover is formatting of a Date object (which is added to the Spring model parameters).
我们要讨论的第一个函数是对java.util.Date对象的处理。负责日期处理的表达式实用对象以#dates.functionName().开头。我们要讨论的第一个函数是日期对象的格式化(该对象被添加到Spring模型的参数中)。
Let’s say we want to use ISO8601 format:
假设我们想使用ISO8601格式。
<p th:text="${#dates.formatISO(date)}"></p>
No matter how our date was set on the back-end side, it needs to be displayed accordingly to this standard. What’s more, if we want to be specific with the format, we can specify it manually:
无论我们的日期在后端是如何设置的,它都需要根据这个标准来显示。更重要的是,如果我们想对格式有特殊要求,我们可以手动指定。
<p th:text="${#dates.format(date, 'dd-MM-yyyy HH:mm')}"></p>
The function takes two variables as parameters: Date and its format.
该函数需要两个变量作为参数。日期和其格式。
Finally, here are a few similarly useful functions we can use:
最后,这里有几个类似的有用功能,我们可以使用。
<p th:text="${#dates.dayOfWeekName(date)}"></p>
<p th:text="${#dates.createNow()}"></p>
<p th:text="${#dates.createToday()}"></p>
In the first, we will receive the name of the day of the week, in the second we will create a new Date object, and finally we will create a new Date with time set to 00:00.
在第一个中,我们将收到一周中的一天的名称,在第二个中,我们将创建一个新的Date对象,最后我们将创建一个新的Date,时间设置为00:00。
3.2. Calendar Objects
3.2.日历对象
Calendar utilities are very similar to dates processing, except that we are using an instance of the java.util.Calendar object:
日历工具与日期处理非常相似,只是我们使用的是java.util.Calendar对象的一个实例。
<p th:text="${#calendars.formatISO(calendar)}"></p>
<p th:text="${#calendars.format(calendar, 'dd-MM-yyyy HH:mm')}"></p>
<p th:text="${#calendars.dayOfWeekName(calendar)}"></p>
The only difference is when we want to create new Calendar instance:
唯一的区别是当我们想创建新的Calendar实例时。
<p th:text="${#calendars.createNow().getTime()}"></p>
<p th:text="${#calendars.createToday().getFirstDayOfWeek()}"></p>
Please note, that we may use any Calendar class method in order to get requested data.
请注意,我们可以使用任何Calendar类方法来获得所要求的数据。
3.3. Numbers Processing
3.3.数字处理
Another very handful feature is numbers-processing. Let’s focus on a num variable, randomly created with a double type:
另一个非常方便的功能是数字处理。让我们关注一个num变量,随机创建一个double类型。
<p th:text="${#numbers.formatDecimal(num,2,3)}"></p>
<p th:text="${#numbers.formatDecimal(num,2,3,'COMMA')}"></p>
In the first line, we format decimal number by setting minimum integer digits and exact decimal digits. In the second one, in addition to integer and decimal digits, we specified the decimal separator. The options are POINT, COMMA, WHITESPACE, NONE or DEFAULT (by locale).
在第一行中,我们通过设置最小整数位和精确的小数位来格式化小数。在第二行中,除了整数和小数位,我们还指定了小数分隔符。选项有POINT、COMMA、WHITESPACE、NONE或DEFAULT(根据地区设置)。
There is one more function that we want to present in this paragraph. It is creation of a sequence of integer numbers:
在本段中,我们还想介绍一个功能。它是创建一个整数的序列。
<p th:each="number: ${#numbers.sequence(0,2)}">
<span th:text="${number}"></span>
</p>
<p th:each="number: ${#numbers.sequence(0,4,2)}">
<span th:text="${number}"></span>
</p>
In the first example, we had Thymeleaf generate a sequence from 0-2, whereas in the second in addition to minimum and maximum value, we provided a definition of step (in this example the values will change by two).
在第一个例子中,我们让Thymeleaf生成一个0-2的序列,而在第二个例子中,除了最小值和最大值之外,我们还提供了一个步骤的定义(在这个例子中,数值将以2为单位变化)。
Please note, that the interval is closed on both sides.
请注意,该区间的两边都是封闭的。
3.4. Strings Operations
3.4.字符串操作
It is the most comprehensive feature of expression utility objects.
它是表达实用对象的最全面的特征。
We can start the description with the utility of checking empty or null String objects. Quite often, developers would use Java methods inside Thymeleaf tags to do that, which might be not safe for null objects.
我们可以从检查空或null String对象的效用开始描述。很多时候,开发者会在Thymeleaf标签内使用Java方法来做这件事,这对null对象来说可能不安全。
Instead, we can do this:
相反,我们可以这样做。
<p th:text="${#strings.isEmpty(string)}"></p>
<p th:text="${#strings.isEmpty(nullString)}"></p>
<p th:text="${#strings.defaultString(emptyString,'Empty String')}"></p>
The first String is not empty, so the method will return false. The second String is null, so we will get true. Finally, we may use #strings.defaultString(…) method to specify a default value, if String will be empty.
第一个String不是空的,所以这个方法将返回false。第二个字符串是空的,所以我们将得到真。最后,我们可以使用#strings.defaultString(…)方法来指定一个默认值,如果String将为空。
There are many more methods. All of them works not only with strings but also with Java.Collections. For example to use substring-related operations:
还有很多方法。所有这些方法不仅适用于字符串,也适用于Java.Collection。例如,使用与子串相关的操作。
<p th:text="${#strings.indexOf(name,frag)}"></p>
<p th:text="${#strings.substring(name,3,5)}"></p>
<p th:text="${#strings.substringAfter(name,prefix)}"></p>
<p th:text="${#strings.substringBefore(name,suffix)}"></p>
<p th:text="${#strings.replace(name,'las','ler')}"></p>
or to use null-safe comparison and concatenation:
或使用空安全的比较和连接。
<p th:text="${#strings.equals(first, second)}"></p>
<p th:text="${#strings.equalsIgnoreCase(first, second)}"></p>
<p th:text="${#strings.concat(values...)}"></p>
<p th:text="${#strings.concatReplaceNulls(nullValue, values...)}"></p>
Finally, there are text-style related features, that will preserve the syntax to be always the same:
最后,还有一些与文本风格相关的功能,这些功能将保持语法始终不变。
<p th:text="${#strings.abbreviate(string,5)} "></p>
<p th:text="${#strings.capitalizeWords(string)}"></p>
In the first method, abbreviated text will make it have a maximum size of n. If a text is bigger, it will be clipped and finished with “…”.
在第一种方法中,缩写的文本将使它的最大尺寸为n。如果一个文本更大,它将被剪掉并以”… “结束。
In the second method, we will capitalize words.
在第二种方法中,我们将把单词大写。
3.5. Aggregates
3.5.集合体
The last but not the least function that we want to discuss here is aggregates. They are null safe, and provide utilities to calculate average or sum from array or any other collection:
我们在这里要讨论的最后一个但并非最不重要的函数是aggregates。它们是null安全的,并提供了从数组或任何其他集合中计算平均值或总和的工具。
<p th:text="${#aggregates.sum(array)}"></p>
<p th:text="${#aggregates.avg(array)}"></p>
<p th:text="${#aggregates.sum(set)}"></p>
<p th:text="${#aggregates.avg(set)}"></p>
4. Conclusion
4.结论
In this article, we discussed Expression Utility Objects features implemented in the Thymeleaf framework, version 3.0.
在这篇文章中,我们讨论了在Thymeleaf框架3.0版本中实现的表达式实用对象功能。
The full implementation of this tutorial can be found in the GitHub project.
本教程的完整实现可以在GitHub项目中找到。
How to test? Our suggestion is to play with a browser first, then check the existing JUnit tests as well.
如何测试?我们的建议是先用浏览器玩一玩,然后也检查一下现有的JUnit测试。
Please take a note, that examples do not cover all available utility expressions. If you want to learn about all types of utilities have a look here.
请注意,这些例子并没有涵盖所有可用的实用程序表达式。如果你想了解所有类型的实用程序,请看这里。