spring boot 语言国际化操作

        最近在学习spring boot的技术,这里整理一下spring boot中的国际化,方便以后使用国际化时,可以直接调用或者加以参考,缩短开发时间。

        首先是编写国际化的资源文件,通常将其放在i18n文件夹下,然后定义一个properties文件,使用国际化时,遵守相关的约定,IDEA工具以及spring boot会自动帮我们识别这个国际化资源文件。其约定是:文件名.properties(这个为默认的国际化文件),然后是 文件名_语言代码_国家代码.properties(例:messages_zh_CN.properties)。下图是IDEA工具识别到为国际化资源文件后,提供的一个便捷操作:

        这里国际化资源我的命名是lang,如果这里进行了命名,就要在application.properties中修改spring.messages.basename的值,我的是放在i18n文件夹下并命名为lang的,故spring.messages.basename=i18n.lang,如果不在配置文件中进行修改,那么就识别不到该国际化资源文件,原因如下:

public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
            String basename = context.getEnvironment().getProperty("spring.messages.basename", "messages");
            ConditionOutcome outcome = (ConditionOutcome)cache.get(basename);
            if(outcome == null) {
                outcome = this.getMatchOutcomeForBasename(context, basename);
                cache.put(basename, outcome);
            }

            return outcome;
        }

        在MessageSourceAutoConfiguration类中,资源文件名就是从配置文件中读取的,配置文件若对basename没有命名,就默认为messages,若命名了,则改为所命名的。

        debug操作如图:

        因此,如果不想修改配置文件,那么就将国际化的相关资源文件的前缀统一命名为messags即可。

        要实现国际化效果,需要实现LocaleResolver这个接口,只需要重写resolverLocale这个方法即可,在前台定义请求参数,设定好中英文,代码中使用了thymeleaf语法,等同于a标签的超链接传参

<a class="btn btn-sm" th:href="@{/index.html(lang='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/index.html(lang='en_US')}">English</a>

        后台处理这个参数,通过参数的值来选择语言。

public class MyLocaleResolver implements LocaleResolver {
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        String lang = request.getParameter("lang");
        Locale locale = Locale.getDefault();
        if(lang!=null&&lang.length()==5){
            String[] split = lang.split("_");
            locale = new Locale(split[0],split[1]);
        }
        return locale;
    }

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

        后台就已经完成了处理,前台只需要对语言资源文件进行引用就可以了,下方代码是thymeleaf引用国际化资源。

<h1 th:text="#{lang.tip}">Please sign in</h1>

        当然,可以选择自己的方式进行前后台的逻辑处理。

        最后,记得将这个自定义的国际化的类加入到容器中,在自己定义的MvcConfig中,添加

    @Bean
    public LocaleResolver localeResolver(){

        return new MyLocaleResolver();
    }

        使得spring boot可以将其注册到容器中。

猜你喜欢

转载自blog.csdn.net/a15123837995/article/details/83617595