6. Page internationalization
Sometimes, our website will involve the switching between Chinese and English or even multiple languages. At this time, we need to internationalize the page design.
6.1 preparation
Uniformly set the encoding format of properties in IDEA
6.2 preparation of configuration files
Write an internationalization configuration file and extract the page information that needs to be internationalized. You can go to the login page to see what content needs to be internationalized!
Step 1
We create a new i18n directory (folder) under the resources resource file to store the internationalization configuration file
Step 2
Create a new login.properties file in the i18n directory, and then create another login in the same way_ zh_ Cn.properties. At this time, IDEA automatically recognizes that we want to do internationalization, and the folder level has changed!
Step 3
We can create a new file in the Resource Bundle 'login' directory in English
The following page pops up, and we add an English one: en_US
Added successfully
Step 4
Next, write the configuration, and we can see another view under the idea
Enter this view and click the + sign to add attributes directly. Create a new login.btn. You can see that there are three file boxes on the right for input, and then add other page attribute contents in turn!
View our configured files
login.properties: default
login.btn=Sign in login.password=password login.remember=Remember me login.tip=Please login login.username=user name
login_en_US.properties: English
login.btn=Sign in login.password=Password login.remember=Remember me login.tip=Please sign in login.username=Username
login_zh_CN.properties: Chinese
login.btn=Sign in login.password=password login.remember=Remember me login.tip=Please login login.username=user name
OK, the configuration file steps are completed!
6.3 research on the effectiveness of configuration file
First, let's take a look at the automatic configuration of internationalization by SpringBoot. This involves a class: MessageSourceAutoConfiguration, which has a method. It is found that SpringBoot has automatically configured the component ResourceBundleMessageSource for managing internationalization resource files;
// Get the value passed from properties to judge @Bean @ConfigurationProperties(prefix = "spring.messages") public MessageSourceProperties messageSourceProperties() { return new MessageSourceProperties(); } @Bean public MessageSource messageSource(MessageSourceProperties properties) { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); if (StringUtils.hasText(properties.getBasename())) { // Set the basic name of the internationalization file (excluding the language country code) messageSource.setBasenames(StringUtils .commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(properties.getBasename()))); } if (properties.getEncoding() != null) { messageSource.setDefaultEncoding(properties.getEncoding().name()); } messageSource.setFallbackToSystemLocale(properties.isFallbackToSystemLocale()); Duration cacheDuration = properties.getCacheDuration(); if (cacheDuration != null) { messageSource.setCacheMillis(cacheDuration.toMillis()); } messageSource.setAlwaysUseMessageFormat(properties.isAlwaysUseMessageFormat()); messageSource.setUseCodeAsDefaultMessage(properties.isUseCodeAsDefaultMessage()); return messageSource; }
Our real situation is that it is placed in the i18n directory under resources, so we need to configure the path of messages in application.properties
# The real location of our internationalization profile spring.messages.basename=i18n/login
6.4 configuring page internationalization values
Go to the page to get the internationalization value, check the Thymeleaf document, and find the message value. The operation is: #{xxx}
6.5 configuration internationalization analysis
In Spring, there is an international Locale (region information object), which has a parser called Locale resolver (get region information object)!
Let's go to our webmvc automatic configuration file and look for it! See the SpringBoot default configuration:
@Bean @ConditionalOnMissingBean @ConditionalOnProperty(prefix = "spring.mvc", name = "locale") public LocaleResolver localeResolver() { // If there is no self configuration in the container, use the user configuration if (this.mvcProperties.getLocaleResolver() == WebMvcProperties.LocaleResolver.FIXED) { return new FixedLocaleResolver(this.mvcProperties.getLocale()); } // Receiver header internationalization decomposition AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver(); localeResolver.setDefaultLocale(this.mvcProperties.getLocale()); return localeResolver; }
There is a method in the AcceptHeaderLocaleResolver class
public Locale resolveLocale(HttpServletRequest request) { Locale defaultLocale = this.getDefaultLocale(); // By default, the Locale is obtained according to the region information brought by the request header for internationalization if (defaultLocale != null && request.getHeader("Accept-Language") == null) { return defaultLocale; } else { Locale requestLocale = request.getLocale(); List<Locale> supportedLocales = this.getSupportedLocales(); if (!supportedLocales.isEmpty() && !supportedLocales.contains(requestLocale)) { Locale supportedLocale = this.findSupportedLocale(request, supportedLocales); if (supportedLocale != null) { return supportedLocale; } else { return defaultLocale != null ? defaultLocale : requestLocale; } } else { return requestLocale; } } }
If we want to click the link to make our international resources effective now, we need to make our own Locale effective!
Let's write our own locale resolver, which can carry regional information on the link!
Modify the jump link of the front page:
Let's write a component class for processing!
package com.dzj.config; import org.springframework.web.servlet.LocaleResolver; import org.thymeleaf.util.StringUtils; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Locale; public class MyLocaleResolver implements LocaleResolver { @Override public Locale resolveLocale(HttpServletRequest request) { //Gets the language parameter in the request String language = request.getParameter("l"); Locale locale = Locale.getDefault();//If not, use the default //If the requested link carries internationalization parameters if(!StringUtils.isEmpty(language)){ //zh_CN String[] split = language.split("_"); // Language, country locale = new Locale(split[0], split[1]); } return locale; } @Override public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) { } }
In order for our regionalization information to take effect, we need to configure this component again! Add bean s under our own mvcconfig;
package com.dzj.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class MyMvcConfig implements WebMvcConfigurer { //The customized internationalization component takes effect @Bean public LocaleResolver localeResolver(){ return new MyLocaleResolver(); } }
Here, the writing of international configuration is completely done!