SpringBoot special study Part16: SpringBoot achieve international language switching function (i18n)

What is internationalization

It sounds very big on the international fact-language information is through the browser to display dynamic effect of international
popular it is, click on the button when the show Chinese Chinese English click on the button when the display in English (of course also supports other languages

International implementation steps:

  • 1), to prepare an international profile
  • 2) using ResourceBundleMessageSource international management of the resource file
  • 3) Remove the internationalization of the content on the page

Inside SpringBoot has achieved the first step 2 and step 3 to its bottom has been configured and therefore only need to write an international profile

First, the preparation of an international profile

Writing International profile is drawn international news page to be displayed
Popular, is to be "translated" text extract

In the resources to create a resource directory for storing packet international profile
and then create a profile login.properties
naming format: page name _ _ language code country code .properties

When IDEA recognizes it will automatically switch to the internationalization of view
Here Insert Picture Description
this is the case can be just right to create an international profile
right, click the plus sign (+)
Here Insert Picture Description
input language code _ country code can be automatically generated configuration file
Here Insert Picture Description
can then in the lower left profile click Resource Bundle switching angle view
Here Insert Picture Description
click on the top left of the plus sign (+) to add a language configuration
Here Insert Picture Description
so configured models to copy all need to convert the language section
Here Insert Picture Description

Second, the automatic internationalization

SpringBoot has been automatically configured the component manages an international resource files

Autoconfiguration underlying code language resource class is as follows:

@ConfigurationProperties(prefix = "spring.messages")
public class MessageSourceAutoConfiguration {
    
    /**
	 * Comma-separated list of basenames (essentially a fully-qualified classpath
	 * location), each following the ResourceBundle convention with relaxed support for
	 * slash based locations. If it doesn't contain a package qualifier (such as
	 * "org.mypackage"), it will be resolved from the classpath root.
	 */
	private String basename = "messages";  
    ...
}

The default profile can be seen on the basis named messages
based configuration file name is the name of removing e.g. zh_CN
available spring.messages configure the
base name may comprise the name if the package contains the classes from the path-finding

Then go to the configuration file configuration :
Example: spring.messages.basename=i18n.login
The significance of the path is configured to find the foundation named login configuration file from the i18n package
is designed to allow SpringBoot can find our international profile configuration

Third, access to international value of the page

Thymeleaf of #{}grammar is used to obtain an international information
so the value can easily get to the international

Use th: expression to be replaced
Here Insert Picture Description
so you can automatically internationalization

Garbage problem:

IDEA default will not be converted to ASCII code Chinese thus causing garbled
select File Encoding in the settings and then select the Automatically converts ASCII code
Here Insert Picture Description
so that the default configuration is based on the browser's language
browser with what language is then automatically identify as the default language
Here Insert Picture Description
Here Insert Picture Description

Of course, you can also manually click the button to switch the language

This feature on some of the more common trade website

Principle:
international Locale area information object which has a LocaleResolver components used to obtain area information object

The default configuration is also SpringBoot area information parser
underlying code:

@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = "spring.mvc", name = "locale")
public LocaleResolver localeResolver() {
    if (this.mvcProperties.getLocaleResolver() == WebMvcProperties.LocaleResolver.FIXED) {
        return new FixedLocaleResolver(this.mvcProperties.getLocale());
    }
    AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
    localeResolver.setDefaultLocale(this.mvcProperties.getLocale());
    return localeResolver;
}

Means that when the designated fixed area parser uses a fixed otherwise use AcceptHeaderLocaleResolver
and AcceptHeaderLocaleResolver Locale is to obtain information from the browser's request header followed by an international
because the head will Accept Language with a browser request when sending the request field inside the browser's default language
AcceptHeaderLocaleResolver is to identify the browser by default this language

So just to replace LocaleResolver to

Needed at the front end carries the information on the link area switching button

<a class="btn btn-sm" th:href="@{/index.html(language=zh_CN)}">中文</a>
<a class="btn btn-sm" th:href="@{/index.html(language=en_US)}">English</a>

When click on the link to switch language will bring the language parameter to send the request

So the following URL will be able to carry the information area:

http://ip:端口/XXXX/index.html?language=zh_CN

Then the back end must create its own area parser class implement the interface LocaleResolver
directly on the code:

public class MyLocaleResolver implements LocaleResolver {

    // 解析区域信息
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        // 从URL的参数中获取区域信息
        String language = request.getParameter("language");
        // 区域信息默认用系统识别的
        Locale locale=Locale.getDefault();
        // 若获取的区域参数不为空 即 URL带有区域信息
        if (!StringUtils.isEmpty(language))
        {
            // 根据中间的下划线分隔成两部分
            String[] s = language.split("_");
            locale=new Locale(s[0],s[1]);
        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {

    }
}

Then add your own parser class area to write in your own configuration class in the Spring container (remember to add @Bean comment)

@Bean
public LocaleResolver localeResolver()
{
        // 直接返回自己配置的区域解析器
        return new MyLocaleResolver();
}

So configure your own area parser be able to work out SpringBoot will replace the built-in parser regional
final effect is achieved when the URL is not with regional information automatically depending on the browser URL with area information is used to specify the language when language recognition


Published 174 original articles · won praise 5 · Views 240,000 +

Guess you like

Origin blog.csdn.net/Piconjo/article/details/104934578