欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

errorsk-4nQwBFp0LP8NpyK9WwwoT3BlbkFJyH23SKdFWR1P9Sr63sF8

最编程 2024-08-13 07:28:32
...

3.1建立语言的资源文件

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

如图所示,sysmsg.properties为默认语言模式,当系统没找到相对应的语言文件时,将调用本文件的数据。

sysmsg_en_US.properties为英文资源文件,sysmsg.properties_zh_CN为中文语言文字。

3.2国际化语言配置
3.2.1创建MessageUtils工具类
MessageUtils主要作用是在后台通过key来获取目前系统语言的value值。



 public class MessageUtils {

   private final MessageSource messageSource;

   public MessageUtils(MessageSource messageSource) {
       this.messageSource = messageSource;
   }

   public String getMessage(String msgKey, Object[] args) {
       return messageSource.getMessage(msgKey, args, LocaleContextHolder.getLocale());
   }

   public String getMessage(String msgKey) {
       return messageSource.getMessage(msgKey, null, LocaleContextHolder.getLocale());
   }
}

3.2.2创建本地语言的配置类LocaleConfig,用于配置i18n的设置
(1)MessageUtils注入容器。

(2)设置i18资源文件读取的路径。(messageSource()方法)

(3)设置默认本地语言解析器。唯有配置了这个才能系统可以根据浏览器的默认语言设置进行语言切换。(localeResolver()方法)

(4)默认拦截器 其中lang表示切换语言的参数名。(localeInterceptor())

@Configuration
public class LocaleConfig {

   @Bean
   public MessageUtils messageUtils() {
       return new MessageUtils(messageSource());
   }

 /**
 *资源文件路径
 **/
   @Bean
   public ResourceBundleMessageSource messageSource() {
       Locale.setDefault(Locale.CHINESE);
       ResourceBundleMessageSource source = new ResourceBundleMessageSource();
       /*ame of the resource bundle*/
       source.setBasenames("i18n/sysmsg","i18n/userGeneral", "i18n/pageGeneral", "i18n/webValidator");
       //默认是false,调试设置为true
       source.setUseCodeAsDefaultMessage(true);
       source.setDefaultEncoding("UTF-8");
       return source;
   }


   /**
     * 默认解析器 其中locale表示默认语言
     */
   @Bean
   public LocaleResolver localeResolver() {
       SessionLocaleResolver localeResolver = new SessionLocaleResolver();
       // localeResolver.setDefaultLocale(Locale.UK);
       return localeResolver;
   }

   /**
     * 默认拦截器 其中lang表示切换语言的参数名
     */
   @Bean
   public WebMvcConfigurer localeInterceptor() {
       return new WebMvcConfigurerAdapter() {
           @Override
           public void addInterceptors(InterceptorRegistry registry) {
               LocaleChangeInterceptor localeInterceptor = new LocaleChangeInterceptor();
               localeInterceptor.setParamName("lang");
               registry.addInterceptor(localeInterceptor);
           }
       };
   }
}

3.2.3freemarker页面引入 spring.ftl
spring.ftl文件主要作用于在前端页面获取资源文件中的语言文字, spring.ftl文件位置复制到 resources/static 文件夹下 。spring.ftl文件位于:

在这里插入图片描述

页面上引入<#import “spring.ftl” as spring>

页面上取值roperties文件中的变量值的方法为:<@spring.message code=“login.tip” />