banner
jzman

jzman

Coding、思考、自觉。
github

Spring Boot Series: Project Internationalization

PS: On the 21st, Bank of China's Crude Oil Treasure encountered the lowest settlement price in history, settling at -37.63 US dollars per barrel. Investors are required to close their positions at a settlement price of -266.12 yuan per barrel and are subsequently sent a text message requesting immediate payment of the delivery amount. This means that investors not only lose all their margin, but also have to pay an additional -266 yuan per barrel. There is an investment common sense here: if you don't understand, don't invest, and don't blindly try to buy at the bottom.

In the previous articles, we explored interface development, Thymeleaf templates, common syntax, and template layouts. Before reading this article, you can read the previous ones:

Implementing internationalization in a Spring Boot project is very simple. In order to maintain the continuity of the Spring Boot series, internationalization in the project is discussed in a separate article, with the main content as follows:

  1. Locale Resolver
  2. Creating Internationalization Configuration Files
  3. Creating Configuration Classes
  4. Testing the Effect

Locale Resolver#

Spring provides a locale resolver to identify the user's locale and achieve internationalization of web applications. The locale resolver must implement the LocalResolver interface, or you can implement your own locale resolver.

  • AcceptHeaderLocaleResolver: Default locale resolver, which resolves the locale based on the accept-language parameter of the HTTP request.
  • SessionLocaleResolver: Effective within the current session, otherwise it reverts to the default state.
  • CookieLocaleResolver: Effective within the current cookie validity period, otherwise it reverts to the default state.
  • FixedLocaleResolver: Sets a fixed Locale, which is not convenient for dynamically changing the Locale.
  • Use the LocaleChangeInterceptor interceptor to resolve the user's locale.

Next, we will use the LocaleChangeInterceptor interceptor and SessionLocaleResolver as examples to implement internationalization in a Spring Boot project.

Creating Internationalization Configuration Files#

Spring Boot supports internationalization and is also relatively easy to use. Create a Spring Boot project and create a folder named "i18n" under resources. Then, right-click and select New->Resource Bundle to create a home.properties file for each language, as shown below:

Image

Then, in the application.properties file, configure the Message path as follows:

# Message path
spring.messages.basename=i18n.home

How to retrieve the values in the home.properties file? Like this:

mMessageSource.getMessage("home.title", null, LocaleContextHolder.getLocale());

Creating Configuration Classes#

Use the LocaleChangeInterceptor interceptor and SessionLocaleResolver, and set the corresponding Locale as the parameters, as shown below:

/**
 * I18nConfig
 */
@Configuration
public class I18nConfig {

    @Bean
    public LocaleResolver localeResolver (){
        return new SessionLocaleResolver();
    }

    @Bean
    public WebMvcConfigurer webMvcConfigurer(){
        return new WebMvcConfigurer() {
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                LocaleChangeInterceptor changeInterceptor = new LocaleChangeInterceptor();
                changeInterceptor.setParamName("lang");
                registry.addInterceptor(changeInterceptor);
            }
        };
    }
}

Sample Code#

I18nController as follows:

@Controller
public class I18nController {
    
    @GetMapping(value = "/i18n")
    public String il8n() {
        return "i18n";
    }
}

The template file is as follows:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
	<head>
		<meta charset="UTF-8">
		<title>Spring Boot I18n Sample.</title>

		<script>
			/**
			 * Called after the page is loaded
			 */
			onload = function() {
				let href = window.location.toString();
				let suffix = href.substring(href.length - 2, href.length);
				let lang = document.getElementsByClassName("lang");
				console.log("--suffix--" + suffix);
				switch (suffix) {
					case "CN":
						setStatus(lang[0], lang[1], lang[2]);
						break;
					case "TW":
						setStatus(lang[1], lang[0], lang[2]);
						break;
					case "US":
						setStatus(lang[2], lang[1], lang[0]);
						break;
					default:
						setStatus(lang[0], lang[1], lang[2]);
				}
			};

			/**
			 * Set the status of language tags
			 * @param show Selected language tag
			 * @param def1 Unselected language tag
			 * @param def2 Unselected language tag
			 */
			function setStatus(show, def1, def2) {
				show.style.color = "rgb(0,0,255)";
				def1.style.color = "rgb(0,0,0)";
				def2.style.color = "rgb(0,0,0)";
			}
		</script>
	</head>
	<body>
		<h3 th:text="#{home.title}">default</h3>
		<p style="font-size: 12px">
			<a class="lang" href="i18n?lang=zh_CN"> Simplified Chinese </a>|
			<a class="lang" href="i18n?lang=zh_TW"> Traditional Chinese </a>|
			<a class="lang" href="i18n?lang=en_US"> English</a>
		</p>
	</body>
</html>

Testing the Effect#

The running effect is as follows:

image

You can add the keyword "加群" in the public account to invite you to join the WeChat exchange group, and reply with the keyword "Spring Boot" to get the corresponding case source code link.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.