国际化技术参考

发布于:2024-07-23 ⋅ 阅读:(137) ⋅ 点赞:(0)

一、概述

国际化就是用户可以选择对应的语言,页面展示成对应的语言;

一个系统的国际化按照信息的所在位置,可以分为三种国际化信息:

  • 前端页面信息
  • 后端提示信息
  • 数据库的字典类信息

二、前端页面国际化

使用i18n库实现国际化

  • i18n国际化库思路:

通过jquery或者dom操作拿到需要变化语种的id或者class,然后到配置文件里面识别key是谁,因为他的结构是map结构的,也就是value-key的结构,最后在html页面通过class或者id取到名字就行了;

相关技术可以看博客:https://blog.csdn.net/qq_41485414/article/details/81093999

也可以直接在网上搜索关键词:前端i18n国际化

三、后端提示信息国际化

依托于Spring的国际化技术实现

3.1 创建语言信息包

  • 在项目的resources下创建文件夹 i18n

  • i18n文件夹下创建 messages语言信息包

    使用idea创建:
    在这里插入图片描述
    在这里插入图片描述
    创建完成后,既可看到两类语言的配置文件:
    在这里插入图片描述

配置内容可以按照需要增加 键值对,例如:

  • messages_en_US.properties
return.ok=Success
return.fail=FAIL
  • messages_zh_CN.properties
return.ok=操作成功
return.fail=操作失败
  • 国际化i18n语言码表:

i18n语言码表

3.2 注入语言资源类

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;

import java.util.Locale;

/**
 * @author xch
 * 2024/7/18 14:15
 */
@Configuration
public class LocaleConfig {
   
    @Bean
    public ResourceBundleMessageSource messageSource() {
   
        //默认使用 中文
        Locale.setDefault(Locale.CHINA);
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setBasename("i18n/messages");
        messageSource.setDefaultEncoding("UTF-8");
        messageSource.setUseCodeAsDefaultMessage(true);
        return messageSource;
    }
}
  • 原理是,Spring会创建一个MessageSource的bean;这个MessageSource提供了对应的语言转换方法:
@Nullable
String getMessage(String code, @Nullable Object[] args, @Nullable String defaultMessage, Locale locale);

String getMessage(String code, @Nullable Object[] args, Locale locale) throws NoSuchMessageException;

String getMessage(MessageSourceResolvable resolvable, Locale locale) throws NoSuchMessageException;

code:我们在语言信息包中配置的key,如:return.ok

local:就是我们要转换的对应的语言

所以我们使用的时候只需调用上面的getMessage方法既可实现信息国际化;

3.3 示例(不优雅)

为了方便使用上述的getMessage方法,可以封装成静态的方法,方便调用使用:

  • 封装SpringUtil工具类
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * @author xch
 * 2024/7/19 16:10
 */
@Component
public class SpringUtil implements ApplicationContextAware {
   
    private static ApplicationContext applicationContext = null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
   
        if (SpringUtil.applicationContext == null) {
   
            SpringUtil.applicationContext = applicationContext;
        }
    }

    /**
     * 通过class获取Bean.
     */
    public static <T> T getBean(Class<T> clazz) {
   
        return applicationContext.getBean(clazz);
    }

网站公告

今日签到

点亮在社区的每一天
去签到