1. Introduction
1.绪论
In this tutorial, we’ll learn how to format currencies by locale using Thymeleaf.
在本教程中,我们将学习如何使用Thymeleaf按地区设置货币格式。
2. Maven Dependencies
2.Maven的依赖性
Let’s begin by importing the Spring Boot Thymeleaf dependency:
让我们首先导入Spring Boot Thymeleaf依赖项。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.2.7.RELEASE</version>
</dependency>
3. Project Setup
3.项目设置
Our project will be a simple Spring web application that displays currencies based on the user’s locale. Let’s create our Thymeleaf template, currencies.html, in resources/templates/currencies:
我们的项目将是一个简单的Spring Web应用,根据用户的地域显示货币。让我们在resources/templates/currencies中创建我们的Thymeleaf模板,currencies.html。
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Currency table</title>
</head>
</html>
We can also create a controller class that will handle our requests:
我们还可以创建一个控制器类,来处理我们的请求。
@Controller
public class CurrenciesController {
@GetMapping(value = "/currency")
public String exchange(
@RequestParam(value = "amount") String amount, Locale locale) {
return "currencies/currencies";
}
}
4. Formatting
4.格式化
When it comes to currencies, we need to format them based on the requester’s locale.
当涉及到货币时,我们需要根据请求者的地域来格式化它们。
In this case, we’ll send the Accept-Language header with each request to represent our user’s locale.
在这种情况下,我们将在每个请求中发送Accept-Language头,以代表我们用户的地域。
4.1. Currency
4.1.货币
The Numbers class, provided by Thymeleaf, has support for formatting currencies. So, let’s update our view with a call to the formatCurrency method
Thymeleaf提供的Numbers类,支持格式化货币。因此,让我们通过调用formatCurrency方法来更新我们的视图
<p th:text="${#numbers.formatCurrency(param.amount)}"></p>
When we run our example, we’ll see the currency properly formatted:
当我们运行我们的例子时,我们将看到货币的正确格式化。
@Test
public void whenCallCurrencyWithUSALocale_ThenReturnProperCurrency() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/currency")
.header("Accept-Language", "en-US")
.param("amount", "10032.5"))
.andExpect(status().isOk())
.andExpect(content().string(containsString("$10,032.50")));
}
Since we set the Accept-Language header to the United States, the currency is formatted with a decimal point and a dollar sign.
由于我们将Accept-Language标头设置为美国,所以货币的格式是小数点和美元符号。
4.2. Currency Arrays
4.2.货币数组
We can also use the Numbers class to format arrays. As a result, we’ll add another request parameter to our controller:
我们也可以使用Numbers类来格式化数组。因此,我们将在我们的控制器中添加另一个请求参数。
@GetMapping(value = "/currency")
public String exchange(
@RequestParam(value = "amount") String amount,
@RequestParam(value = "amountList") List amountList, Locale locale) {
return "currencies/currencies";
}
Next, we can update our view to include a call to the listFormatCurrency method:
接下来,我们可以更新我们的视图,包括对listFormatCurrency方法的调用。
<p th:text="${#numbers.listFormatCurrency(param.amountList)}"></p>
Now let’s see what the result looks like:
现在让我们看看结果是什么样子的。
@Test
public void whenCallCurrencyWithUkLocaleWithArrays_ThenReturnLocaleCurrencies() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/currency")
.header("Accept-Language", "en-GB")
.param("amountList", "10", "20", "30"))
.andExpect(status().isOk())
.andExpect(content().string(containsString("£10.00, £20.00, £30.00")));
}
The result shows the currency list with the proper United Kingdom formatting added.
结果显示货币列表中加入了适当的英国格式。
4.3. Trailing Zeros
4.3.尾数零点
Using Strings#replace, we can remove the trailing zeros.
使用Strings#replace,我们可以去掉尾部的零。
<p th:text="${#strings.replace(#numbers.formatCurrency(param.amount), '.00', '')}"></p>
Now we can see the full amount without trailing double zeros:
现在我们可以看到没有尾部双零的全部金额。
@Test
public void whenCallCurrencyWithUSALocaleWithoutDecimal_ThenReturnCurrencyWithoutTrailingZeros()
throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/currency")
.header("Accept-Language", "en-US")
.param("amount", "10032"))
.andExpect(status().isOk())
.andExpect(content().string(containsString("$10,032")));
}
4.4. Decimals
4.4.小数
Depending on the locale, decimals may be formatted differently. Therefore, if we want to replace a decimal point with a comma, we can use the formatDecimal method provided by the Numbers class:
根据不同的地区,小数点的格式可能不同。因此,如果我们想用逗号替换小数点,我们可以使用Numbers类提供的formatDecimal方法。
<p th:text="${#numbers.formatDecimal(param.amount, 1, 2, 'COMMA')}"></p>
Let’s see the outcome in a test:
让我们在测试中看看结果。
@Test
public void whenCallCurrencyWithUSALocale_ThenReturnReplacedDecimalPoint() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/currency")
.header("Accept-Language", "en-US")
.param("amount", "1.5"))
.andExpect(status().isOk())
.andExpect(content().string(containsString("1,5")));
}
The value will be formatted as “1,5”.
该值将被格式化为 “1,5”。
5. Conclusion
5.总结
In this short tutorial, we showed how Thymeleaf can be used with Spring Web to handle currencies using the user’s Locale.
在这个简短的教程中,我们展示了Thymeleaf如何与Spring Web一起使用用户的Locale来处理货币。
As always, the code is available over on GitHub.
像往常一样,代码可在GitHub上获得。