開發與維運

SpringBoot-thymeleaf 基於數據庫國際化

java配置文件

  • 配置攔截器及語言環境解析
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Bean
    public LocaleResolver localeResolver() {
        //設置cookie模式處理國際化
        CookieLocaleResolver cookieLocaleResolver = new CookieLocaleResolver();
        cookieLocaleResolver.setDefaultLocale(Locale.CHINESE);
        return cookieLocaleResolver;
    }
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //指定國際化標識
        LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
        localeChangeInterceptor.setParamName("lang");
        registry.addInterceptor(localeChangeInterceptor);
    }
}
  • 配置國際化數據源
// 1.需指定名稱替換默認bean
@Component("messageSource")
public class DBMessageSource extends AbstractMessageSource {
    // 自定義service
    @Autowired
    private LanguageRepository languageRepository;
    // 2.國際化處理方法依據key在數據庫中查找對應國際化內容
    @Override
    protected MessageFormat resolveCode(String key, Locale locale) {
        LanguageEntity message = languageRepository.findByKeyAndLocale(key,locale.getLanguage());
        if (message == null) {
            message = languageRepository.findByKeyAndLocale(key,Locale.getDefault().getLanguage());
        }
        return new MessageFormat(message.getContent(), locale);
    }
    //3.新增方法,用於後端傳參國際化
    public final String getMessage(String code, @Nullable Object[] args) throws NoSuchMessageException {
        Locale locale = LocaleContextHolder.getLocale();
        String msg = getMessageInternal(code, args, locale);
        if (msg != null) {
            return msg;
        }
        String fallback = getDefaultMessage(code);
        if (fallback != null) {
            return fallback;
        }
        throw new NoSuchMessageException(code, locale);
    }
}

其中3為自己新增的方法用於java代碼中獲取國際化,使用時在java代碼中注入messageSource。

頁面

<h2 th:text="#{home.welcome('xxx')}"></h2>
<p th:text="#{home.info}"></p>
<p th:text="#{home.changelanguage}"></p>
<ul>
    <li><a href="?lang=en" th:text="#{home.lang.en}"></a></li>
    <li><a href="?lang=de" th:text="#{home.lang.de}"></a></li>
    <li><a href="?lang=zh" th:text="#{home.lang.zh}"></a></li>
</ul>

參數傳遞為#{key(參數……)}

問題:

1.Thymeleaf中[[]]為轉義符導致在js代碼中使用國際化並不方便

完整代碼

https://gitee.com/MeiJM/springboot-i18n

參考資料

http://zhangjiaheng.cn/blog/20190320/%E4%BD%BF%E7%94%A8springboot%E8%BF%9B%E8%A1%8C%E5%9B%BD%E9%99%85%E5%8C%96%E6%97%B6%E8%87%AA%E5%AE%9A%E4%B9%89%E8%AF%BB%E5%8F%96%E6%95%B0%E6%8D%AE%E5%BA%93%E9%85%8D%E7%BD%AE/

https://github.com/PhraseApp-Blog/spring-boot-db-messageresource

https://medium.com/techcret/database-aware-i18n-messages-springboot-5715063094ef

Leave a Reply

Your email address will not be published. Required fields are marked *