一、国际化

        1.就是根据不同的浏览器语言,加载不同的配置文件

        2.springboot默认就支持国际化

        3.只需要在resources/目录下创建国际化配置文件即可,名称以messages开始

二、实现国际化(i18n:internationalization)

        1.引入依赖

    <dependency>
            <groupId>org.springframework.boot   </groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <!--依赖不需要传递,子模块需要重新引用-->
            <optional>true</optional>
        </dependency>

        2.创建resources目录下的国际化配置文件

                messages.properties(默认)

                messages_zh_CH.properties(中文)

                messages_en_US.properties(英文)

        3.application.yml中配置

        

spring:
  messages:
    basename: i18n/messages
    encoding: UTF-8

        4.借助freemarker实现国际化

                4.1.在html头部加入<#import "spring.ftl" as s>

                4.2.使用<@s.message code="welcome" />即可

        5.添加拦截器,根据我们选择的语言进行切换

                5.1. I18nLocaleConfig.java

I18nLocaleConfig.java代码如下,直接CV大法即可

@Configuration
public class I18nlocaleConfig {
    @Bean
    public LocaleResolver localeResolver(){
        SessionLocaleResolver resolver = new SessionLocaleResolver();
        resolver.setDefaultLocale(Locale.SIMPLIFIED_CHINESE);
        return resolver;
    }
    //拦截器,请求参数为lang
    @Bean
    public WebMvcConfigurer localeInterceptor(){
        return new WebMvcConfigurer() {
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                LocaleChangeInterceptor interceptor  = new LocaleChangeInterceptor();
                interceptor.setParamName("lang");
                registry.addInterceptor(interceptor);
            }
        };
    }

}

一切准备就绪,我们开始测试:

 运行结果:

发现我这里的中文乱码了,百度了好长时间也没找到解决方法。哪位大佬儿能帮我看看解决一下 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐