代码改变世界

SpringBoot 之 国际化

2020-05-04 11:19  小伍2013  阅读(331)  评论(0编辑  收藏  举报

增加国际化i18n语言配置:

# src/main/resources/i18n/login.properties

login.btn=登录
# src/main/resources/i18n/login_zh_CN.properties

login.btn=登录
# src/main/resources/i18n/login_en_US.properties

login.btn=sign in

在模板中使用国际化语言输出及增加切换语言的链接:

# src/main/resources/templates/index.html

<h1 ... th:text="#{login.tip}"></h1>
<input type="checkbox" value="remember-me"> [[#{login.remember}]]
<button type="submit"> [[#{login.btn}]] </button>

<a th:href="@{/index.html(l='zh_CN')}">中文</a>
<a th:href="@{/index.html(l='en_US')}">English</a>
# src/main/resources/application.properties

# 国际化文件的目录位置
spring.messages.basename=i18n

实现本地化解析器:

# src/main/java/com/wu/config/MyLocaleResolver.java

import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

public class MyLocaleResolver implements LocaleResolver {
    private static final String PATH_PARAMETER = "l";
    private static final String PATH_PARAMETER_SPLIT = "_";

    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        String lang = request.getParameter(PATH_PARAMETER);
        Locale locale = request.getLocale();
        if (!StringUtils.isEmpty(lang)) {
            String[] split = lang.split(PATH_PARAMETER_SPLIT);
            locale = new Locale(split[0], split[1]);
        }
        return locale;
    }

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

    }
}

将语言解析器加入到容器中:

# src/main/java/com/wu/config/MyMvcConfig.java

@Configuration // 标注这个类是一个配置类
public class MyMvcConfig implements WebMvcConfigurer {
    // 配置视图跳转
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/index.html").setViewName("index");
    }

    // 将本地化解析器配置到容器中
    @Bean
    public LocaleResolver localeResolver() {
        return new MyLocaleResolver();
    }

    // 将视图解析器配置到容器中
    @Bean
    public ViewResolver myViewResolver() {
        return new MyViewResolver();
    }

    // 自定义一个视图解析器
    public static class MyViewResolver implements ViewResolver {
        @Override
        public View resolveViewName(String viewName, Locale locale) throws Exception {
            return null;
        }
    }
}