国际化

idea需要安装的插件:Resource Bundle Editor

网站多语言切换。

1. 准备工作

  1. 安装上述的idea插件。
  2. 更改properties的FileEncoding为UTF-8。

2. 开始

  1. 在resources资源文件下新建一个i18n(internationalization缩写)目录,存放国际化配置文件。

  2. 建立login.properties,login_zh_CN.properties,login_en_US.properties。

    idea会识别成Resource Bundle。如果添加了上面提到的插件,可以更改视图,方便同时修改和添加三个配置文件。

    三个配置文件如下

    image-20210925203419058
    Image

    2.1. 配置文件生效探究

    我们去看一下SpringBoot对国际化的自动配置!这里又涉及到一个类:MessageSourceAutoConfiguration

    里面有一个方法,这里发现SpringBoot已经自动配置好了管理我们国际化资源文件的组件

    @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())) {
        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;
    }
    

    由代码看出,需要配置basename

    所以在application.properties中添加

    spring.messages.basename=i18n.login
    
  3. 配置html。

    在Thymeleaf下,message的取值操作为#{}

    image-20210925204838079
    Image
  4. 访问,测试。

  5. 添加自定义切换中英文。

    思路:根据传参的请求进行切换。

    在WebMvcAutoConfiguration类中:

    @Override
    @Bean
    @ConditionalOnMissingBean(name = DispatcherServlet.LOCALE_RESOLVER_BEAN_NAME)
    @SuppressWarnings("deprecation")
    public LocaleResolver localeResolver() {
      // 用户配置了就使用用户配置的国际化配置
      if (this.webProperties.getLocaleResolver() == WebProperties.LocaleResolver.FIXED) {
        return new FixedLocaleResolver(this.webProperties.getLocale());
      }
      if (this.mvcProperties.getLocaleResolver() == WebMvcProperties.LocaleResolver.FIXED) {
        return new FixedLocaleResolver(this.mvcProperties.getLocale());
      }
      // 接受请求头 国际化分解
      AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
      Locale locale = (this.webProperties.getLocale() != null) ? this.webProperties.getLocale()
        : this.mvcProperties.getLocale();
      localeResolver.setDefaultLocale(locale);
      return localeResolver;
    }
    

    在AcceptHeaderLocaleResolver类中:

    @Override
    public Locale resolveLocale(HttpServletRequest request) {
      // 可以看出,默认根据请求头中的Accept-Language返回语言
      Locale defaultLocale = getDefaultLocale();
      if (defaultLocale != null && request.getHeader("Accept-Language") == null) {
        return defaultLocale;
      }
      Locale requestLocale = request.getLocale();
      List<Locale> supportedLocales = getSupportedLocales();
      if (supportedLocales.isEmpty() || supportedLocales.contains(requestLocale)) {
        return requestLocale;
      }
      Locale supportedLocale = findSupportedLocale(request, supportedLocales);
      if (supportedLocale != null) {
        return supportedLocale;
      }
      return (defaultLocale != null ? defaultLocale : requestLocale);
    }
    

    所以,我们需要自定义切换中英文,就需要修改默认的配置。

    编写自己的LocaleReslover。

    参考AcceptHeaderLocaleResolver,继承LocaleResolver类

    public class AcceptHeaderLocaleResolver implements LocaleResolver {
    
    package org.gs.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;
    
    /**
     * @author admin
     * @date 9/25/21 9:02 PM
     */
    public class MyLocaleReslover implements LocaleResolver {
    
        @Override
        public Locale resolveLocale(HttpServletRequest request) {
            Locale locale = Locale.getDefault();
            if (!StringUtils.isEmpty(request.getParameter("lang"))) {
                String[] langs = request.getParameter("lang").split("_");
                // 语言,国家
                locale = new Locale(langs[0], langs[1]);
            }
            return locale;
        }
    
        @Override
        public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
    
        }
    }
    

    在自己的MvcConfig中装配Bean,使之生效。

    package org.gs.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.ViewControllerRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    /**
     * @author admin
     * @date 9/25/21 5:33 PM
     */
    @Configuration
    public class MyMvcConfig implements WebMvcConfigurer {
        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
            registry.addViewController("/").setViewName("index");
            registry.addViewController("/index.html").setViewName("index");
        }
    
        @Bean
        public LocaleResolver localeResolver() {
            return new MyLocaleReslover();
        }
    }
    
Copyright © rootwhois.cn 2021-2022 all right reserved,powered by GitbookFile Modify: 2022-08-10 10:24:47

results matching ""

    No results matching ""