Springboot+freemarker 國際化i18n配置

  • 建立國際化語言配置文件 resources/i18n/ 對應本身的配置文件 分別是 默認,英文,中文,中文繁體

 

  • 在配置 application.properties中指定本身的國際化配置文件
#===============================國際化i18n start =========================================================================
#默認值爲:classpath下的messages_*.properties 本身指定成本身的 類路徑下/i18n/login文件, 自動將login_xx_XX.properties 的後綴忽略只取基礎名稱
spring.messages.basename=i18n/login
spring.messages.encoding=utf-8
#===============================國際化i18n end =========================================================================
  • 向spring容器中加入本身的LocaleResolver
  1. 建立本身的MyLocaleResolver
/**
 * @ClassName: MyLocaleResolver
 * @Description: 自定義地區解析器
 * @author: <a href="liuyafengwy@163.com">luffy</a>
 * @date: 2020/1/15 17:24
 */
public class MyLocaleResolver implements LocaleResolver {

    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        Locale locale = null;
        //獲取參數 locale=en_US
        String localeParameter = request.getParameter("locale");
        if(StrUtil.isNotEmpty(localeParameter)){
            //en_US經過下劃線分割爲數組
            String[] paraArr = localeParameter.split("_");
            locale = new Locale(paraArr[0],paraArr[1]);
        }else{
            //獲取默認 就是瀏覽器中地區語言信息
            locale = request.getLocale();
        }
        return locale;
    }
    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {

    }
}

2.@Bean向容器添加寫好的MyLocaleResolverjava

/**
 * @ClassName:  MyWebMvcConfig
 * @Description:  本身的WebMvc配置類
 * @author:  <a href="liuyafengwy@163.com">luffy</a>
 * @date:  2020/1/15 17:43
 */
@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {

   @Bean
   public LocaleResolver localeResolver(){
      //自定義國際化解析器
      return new MyLocaleResolver();
   }

3.頁面寫入國際化信息變量值spring

freemarker頁面引入spring.ftl數組

spring.ftl文件位置複製到 resources/static 文件夾下瀏覽器

<#--頁面進行引入-->
<#import "spring.ftl" as spring>
<#--頁面取值填寫.properties文件中的變量值-->
<@spring.message code="login.tip" />

默認會使用瀏覽器設置的首選語言個人是中文app

http://127.0.0.1/ide

http://127.0.0.1/?locale=en_US     //locale=en_US 參數會被本身的MyLocaleResolver解析獲得 en_US 設置Locale 頁面對應會使用英文國際化內容spa

http://127.0.0.1/?locale=zh_TWcode

相關文章
相關標籤/搜索