Guide to Internationalization in Spring Boot – Spring Boot中的国际化指南

最后修改: 2017年 3月 18日

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

1. Overview

1.概述

In this quick tutorial, we’re going to take a look at how we can add internationalization to a Spring Boot application.

在这个快速教程中,我们将看看如何向Spring Boot应用程序添加国际化

2. Maven Dependencies

2.Maven的依赖性

For development, we need the following dependency:

对于开发,我们需要以下依赖关系。

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

The latest version of spring-boot-starter-thymeleaf can be downloaded from Maven Central.

spring-boot-starter-thymeleaf 的最新版本可以从Maven中心下载。

3. LocaleResolver

3.LocaleResolver

In order for our application to be able to determine which locale is currently being used, we need to add a LocaleResolver bean:

为了使我们的应用程序能够确定当前使用的是哪种语言,我们需要添加一个LocaleResolverbean。

@Bean
public LocaleResolver localeResolver() {
    SessionLocaleResolver slr = new SessionLocaleResolver();
    slr.setDefaultLocale(Locale.US);
    return slr;
}

The LocaleResolver interface has implementations that determine the current locale based on the session, cookies, the Accept-Language header, or a fixed value.

LocaleResolver接口有一些实现,可以根据会话、cookies、Accept-Language头或一个固定值来确定当前的locale。

In our example, we have used the session based resolver SessionLocaleResolver and set a default locale with value US.

在我们的例子中,我们使用了基于会话的解析器SessionLocaleResolver并设置了一个默认的locale值US

4. LocaleChangeInterceptor

4、LocaleChangeInterceptor

Next, we need to add an interceptor bean that will switch to a new locale based on the value of the lang parameter appended to a request:

接下来,我们需要添加一个拦截器Bean,它将根据附加到请求中的lang参数的值切换到一个新的locale。

@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
    LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
    lci.setParamName("lang");
    return lci;
}

In order to take effect, this bean needs to be added to the application’s interceptor registry.

为了生效,这个Bean需要被添加到应用程序的拦截器注册表中。

To achieve this, our @Configuration class has to implement the WebMvcConfigurer interface and override the addInterceptors() method:

为了实现这一点,我们的@Configuration类必须实现WebMvcConfigurer接口并重写addInterceptors()方法。

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(localeChangeInterceptor());
}

5. Defining the Message Sources

5.定义信息源

By default, a Spring Boot application will look for message files containing internationalization keys and values in the src/main/resources folder.

默认情况下,Spring Boot应用程序将在src/main/resources文件夹中寻找包含国际化键和值的消息文件。

The file for the default locale will have the name messages.properties, and files for each locale will be named messages_XX.properties, where XX is the locale code.

默认语言的文件名称为messages.properties,每个语言的文件名称为messages_XX.properties,其中XX是语言代码。

The keys for the values that will be localized have to be the same in every file, with values appropriate to the language they correspond to.

将被本地化的值的键在每个文件中都必须是相同的,其值与它们所对应的语言相适应。

If a key does not exist in a certain requested locale, then the application will fall back to the default locale value.

如果某个键不存在于某一要求的语言环境中,那么应用程序将退回到默认的语言环境值。

Let’s define a default message file for the English language called messages.properties:

让我们为英语定义一个默认的消息文件,叫做messages.properties

greeting=Hello! Welcome to our website!
lang.change=Change the language
lang.eng=English
lang.fr=French

Next, let’s create a file called messages_fr.properties for the French language with the same keys:

接下来,让我们为法语创建一个名为messages_fr.properties的文件,其键值相同。

greeting=Bonjour! Bienvenue sur notre site!
lang.change=Changez la langue
lang.eng=Anglais
lang.fr=Francais

6. Controller and HTML Page

6.控制器和HTML页面

Let’s create a controller mapping that will return a simple HTML page called international.html that we want to see in two different languages:

让我们创建一个控制器映射,它将返回一个简单的HTML页面,名为 international.html,我们希望看到两种不同语言的页面。

@Controller
public class PageController {

    @GetMapping("/international")
    public String getInternationalPage() {
        return "international";
    }
}

Since we are using thymeleaf to display the HTML page, the locale-specific values will be accessed using the keys with the syntax #{key}:

由于我们使用thymleaf来显示HTML页面,因此将使用语法#{key}的键来访问本地特定的值。

<h1 th:text="#{greeting}"></h1>

If using JSP files, the syntax is:

如果使用JSP文件,其语法为:。

<h1><spring:message code="greeting" text="default"/></h1>

If we want to access the page with the two different locales we have to add the parameter lang to the URL in the form: /international?lang=fr

如果我们想用两种不同的语言访问页面,我们必须在URL中添加参数lang,其形式为: /international?lang=fr

If no lang parameter is present on the URL, the application will use the default locale, in our case US locale.

如果URL上没有lang参数,应用程序将使用默认的locale,在我们的例子中是USlocale。

Let’s add a drop-down to our HTML page with the two locales whose names are also localized in our properties files:

让我们在我们的HTML页面上添加一个下拉菜单,其中有两个地区名称也在我们的属性文件中进行了本地化。

<span th:text="#{lang.change}"></span>:
<select id="locales">
    <option value=""></option>
    <option value="en" th:text="#{lang.eng}"></option>
    <option value="fr" th:text="#{lang.fr}"></option>
</select>

Then we can add a jQuery script that will call the /international URL with the respective lang parameter depending on which drop-down option is selected:

然后我们可以添加一个jQuery脚本,该脚本将根据所选的下拉选项调用 /international URL和相应的lang参数。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
    $("#locales").change(function () {
        var selectedOption = $('#locales').val();
        if (selectedOption != ''){
            window.location.replace('international?lang=' + selectedOption);
        }
    });
});
</script>

7. Running the Application

7.运行应用程序

In order to initialize our application, we have to add the main class annotated with @SpringBootApplication:

为了初始化我们的应用程序,我们必须添加带有@SpringBootApplication注释的主类。

@SpringBootApplication
public class InternationalizationApp {
    
    public static void main(String[] args) {
        SpringApplication.run(InternationalizationApp.class, args);
    }
}

Depending on the selected locale, we will view the page in either English or French when running the application.

根据所选择的地区,我们在运行应用程序时将以英语或法语查看页面。

Let’s see the English version:

让我们看看英文版本。

screen shot in English
And now let’s see the French version:
screen shot in French

8. Conclusion

8.结论

In this tutorial, we have shown how we can use the support for internationalization in a Spring Boot application.

在本教程中,我们已经展示了如何在Spring Boot应用程序中使用对国际化的支持。

The full source code for the example can be found over on GitHub.

该示例的完整源代码可以在GitHub上找到