SpringBoot——Internationalization

High-quality blog posts: IT-BLOG-CN

1. Steps for writing internationalization in Spring

【1】Write international configuration files;
【2】Use ResourceBundleMessageSource to manage internationalized resource files;
【3】Use ftp:message on the page to retrieve the internationalized content;

2. SpringBoot writing internationalization steps

【1】Create the i18n directory, create the login.properties internationalization default configuration file, and create login_zh_CN.properties at the same time. The system will automatically recognize that the configuration is internationalization. It will switch to the internationalization view. You can right-click Resource Bundle 'login'-Add-Add Propertie Files To Resource Bundle to quickly add other internationalization files.

【3】Write an internationalization configuration file and extract the internationalization information that needs to be displayed on the page:

login.btn=Log in
login.password=password
login.remember=remember me
login.tip=please sign in
login.username=username 

3. Principles of internationalization

【1】Enter MessageSourceAutoConfiguration and find that SpringBoot has automatically configured the components for managing international resource configuration files;

@ConfigurationProperties(prefix = "spring.messages")
public class MessageSourceAutoConfiguration {

    /**
     * comma separated list of base names(Essentially a fully qualified classpath location),each followsResourceBundleAgreement,
     * And for position based on slash。if it does not contain the package qualifier(For example“org.mypackage”),It will resolve from the classpath root。
     */
    private String basename = "messages";
    //Our configuration file can be placed directly on the classpath and calledmessages.properties;

    @Bean
    public MessageSource messageSource() {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        if (StringUtils.hasText(this.basename)) {
            //Set the base name of internationalized resource files(Remove the language and country code)
            messageSource.setBasenames(StringUtils.commaDelimitedListToStringArray(
            StringUtils.trimAllWhitespace(this.basename)));
        }
        if (this.encoding != null) {
            messageSource.setDefaultEncoding(this.encoding.name());
        }
        messageSource.setFallbackToSystemLocale(this.fallbackToSystemLocale);
        messageSource.setCacheSeconds(this.cacheSeconds);
        messageSource.setAlwaysUseMessageFormat(this.alwaysUseMessageFormat);
    return messageSource;
} 

【2】If there is Chinese, you need to set the encoding format

Insert image description here

[3] As we can see from the above, we need to set the basename attribute of the internationalized resource in the configuration file:

<span class="hljs-comment"># i18nunder the directorylogindocument</span>
spring.messages.basename=i18n.login 

【4】Go to the page to get the internationalization value (the red part, use #{} for internationalization) (the green part is represented by @{} for links): Effect: Switch internationalization according to the browser language settings.

<!DOCTYPE html>
<html lang="en"  xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta http‐equiv="Content‐Type" content="text/html; charset=UTF‐8">
        <meta name="viewport" content="width=device‐width, initial‐scale=1, shrink‐to‐fit=no">

        <meta name="description" content="">
        <meta name="author" content="">
        <title>Signin Template for Bootstrap</title>
        <!‐‐ Bootstrap core CSS ‐‐>
        <link href="asserts/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="stylesheet">

        <!‐‐ Custom styles for this template ‐‐>
        <link href="asserts/css/signin.css" th:href="@{/asserts/css/signin.css}"rel="stylesheet">
    </head>
    <body class="text‐center">
        <form class="form‐signin" action="dashboard.html">
            <img class="mb‐4" th:src="@{/asserts/img/bootstrap‐solid.svg}" src="asserts/img/bootstrap‐solid.svg" alt="" width="72" height="72">
            <h1 class="h3 mb‐3 font‐weight‐normal" th:text="#{login.tip}">Please signin</h1>
            <label class="sr‐only" th:text="#{login.username}">Username</label>
            <input type="text" class="form‐control" placeholder="Username" th:placeholder="#{login.username}" required="" autofocus="">
            <label class="sr‐only" th:text="#{login.password}">Password</label>
            <input type="password" class="form‐control" placeholder="Password" th:placeholder="#{login.password}" required="">

            <div class="checkbox mb‐3">
                <label>
                   <input type="checkbox" value="remember‐me"/> [[#{login.remember}]]
                </label>
            </div>
            <button class="btn btn‐lg btn‐primary btn‐block" type="submit" th:text="#{login.btn}">Sign in</button>
            <p class="mt‐5 mb‐3 text‐muted">© 2017‐2018</p>
            <a class="btn btn‐sm" th:token tag"></a>
            <a class="btn btn‐sm" th:token tag"></a>
         </form>
    </body>
</html> 

[5] Browser switching can realize the principle of internationalization: internationalized Locale (regional information object), LocaleResolver (obtaining regional information object) enters the WebMvcAutoConfiguration class, SpringBoot is configured with the default localResolve ,as follows:

@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;
} 

【6】When you click “Chinese” or “English” on the page to switch between Chinese and English, refer to the page information in 4). This is where we need to write a Locale ourselves and add it to the container.

/**
 * Can carry zone information on the connection
 */
public class MyLocaleResolver implements LocaleResolver {

    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        String l = request.getParameter("l");
        Locale locale = Locale.getDefault();
        if(!StringUtils.isEmpty(l)){
            String[] split = l.split("_");
            locale = new Locale(split[0],split[1]);
        }
        return locale;
    }
    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
    }
} 

【7】Add the class you wrote to the IOC container. The name of the method must be localeResolver, which is equivalent to the id of bean. It is thought that the default localeResolver will determine whether localeResolver already exists in the container.

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