springboot:i18n国际化

一个 i18n国际化 的 小Demo!

第一步:准备一个SpringBoot项目,如图所示,先在resources下先创建三个语言相关的配置文件

springboot:i18n国际化_第1张图片

第二步:在 application.yml 中配置 i18n国际化(basename为 包名.配置文件名)

#国际化
spring:
  messages:
    basename: i18n.i18n

第三步:写一个语言视图解析器,获取url传递的参数lang,封装成Locale 对象返回

/**
 * 语言视图解析器
 *
 * @author six
 * @date 2022-02-21 10:34
 */
public class MyLocaleResolver implements LocaleResolver {

    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        String lang = request.getParameter("lang");
        System.out.println("=======>lang:"+lang);

        //如果没有就使用默认的
        Locale locale = Locale.getDefault();

        if (!StringUtils.isEmpty(lang)) {
            String[] split = lang.split("-");
            locale = new Locale(split[0],split[1]);
        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {

    }
}

第四步:写一个 config 配置类,获取url传递的参数lang,封装成Locale 对象返回

/**
 * 如果想DIY一些定制化的功能,只要写好这个组件,然后将它交给springboot,springboot会自动装配
 *
 * @author six
 * @date 2022-02-20 22:20
 */
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
    //官方建议扩展springmvc的方式
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/index.html").setViewName("index");
    }

    //自定义的国际化组件就生效了
    @Bean
    public LocaleResolver localeResolver() {
        return new MyLocaleResolver();
    }
}

第五步:随便写一个 index.html 页面(记得在pom.xml导入thymeleaf)


"en" xmlns:th="http://www.thymeleaf.org">

    "UTF-8">
    Title


    

th:text="#{i18n.login}">

th:href="@{/index.html(lang='zh-CN')}">中文 th:href="@{/index.html(lang='en-US')}">English

第六步:看效果

http://localhost:8080/index.html
springboot:i18n国际化_第2张图片http://localhost:8080/index.html?lang=zh-CN
springboot:i18n国际化_第3张图片http://localhost:8080/index.html?lang=en-US
springboot:i18n国际化_第4张图片
OK,完毕!
(个别的不生效或者异常情况,可以是浏览器问题,建议Chrome)

你可能感兴趣的:(SpringBoot,spring,boot,java,后端)