SpringBoot 多语言切换

  若你的web app需要针对当前用户选择的语言进行语言切换, 则例如, 如果语言资源以message带头的, 需要做如下定制:

1/在application.yml里面指定语言资源位置:

2/由于第1点中我将语言资源文件指定为messages/message开关,则需要在resource下的messages文件夹下建立如下语言资源文件,如果只支持英文和简体中文,则需要定义如下资源文件(message.properties必须有,可以为空) :

 

3/建立语言资源访问工具类:

package com.freestyle.common.spring.utils;

import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.support.ResourceBundleMessageSource;

/**
 * 多国语言资源工具
 * Created by rocklee on 2019/9/12 14:46
 */
public class MessageUtil extends ResourceBundleMessageSource {
  private static MessageSource messageSource;

  public static void setMessageSource(MessageSource source){
    messageSource=source;
  }
  public MessageUtil() {
    super();
    //this.messageSource = messageSource;
  }

  /**
   * 获取单个国际化翻译值
   */
  public static String get(String pvsKey) {
    try {
      return messageSource.getMessage(pvsKey, null, LocaleContextHolder.getLocale());
    } catch (Exception e) {
      return pvsKey;
    }
  }
  /**
   * 获取单个国际化翻译值
   */
  public static String get(String pvsKey,Object ... pvParams) {
    try {
      return messageSource.getMessage(pvsKey, pvParams, LocaleContextHolder.getLocale());
    } catch (Exception e) {
      return pvsKey;
    }
  }
}

4/在sb运行加载完毕后为其指定messagesource对象:

@Component
public class ApplicationEvent implements ApplicationListener<ContextRefreshedEvent> {
  @Resource
  protected MessageSource messageSource;
  @Override
  public void onApplicationEvent(ContextRefreshedEvent event) {
    MessageUtil.setMessageSource(messageSource);
    }
}

5/建立本地化配置类

/**
 * 本地化配置
 * Created by rocklee on 2019/9/12 14:33
 */
@Configuration
public class LocaleConfig {
  /**
   * 默认解析器 其中locale表示默认语言
   */
  @Bean
  public LocaleResolver localeResolver() {
    SessionLocaleResolver localeResolver = new SessionLocaleResolver();
    localeResolver.setDefaultLocale(Locale.US);
    return localeResolver;
  }
  /**
   * 默认拦截器 其中lang表示切换语言的参数名
   */
  @Bean
  public WebMvcConfigurer localeInterceptor() {
    return new WebMvcConfigurer() {
      @Override
      public void addInterceptors(InterceptorRegistry registry) {
        LocaleChangeInterceptor localeInterceptor = new LocaleChangeInterceptor();
        localeInterceptor.setParamName("lang");
        registry.addInterceptor(localeInterceptor);
      }
    };
  }

}

客户端切换语言用:

http://192.168.1.2:8889/...?lang=en_US 

http://192.168.1.2:8889/...?lang=zh_CN

 

取message: 

throw new RuntimeException(MessageUtil.get("FGS004",LotStatus.fromValue(lvExists.getF9yStatus()).toString()));

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值