SpringBoot 之 国际化

添加国际化i18n语言配置: # src/main/resources/i18n/login.properties login.btn=登录 # src/main/resources/i18n/login_zh_CN.properties login.btn=登录 # src/main/resources/i18n/...

添加国际化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) {

    }
}

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

# 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;
        }
    }
}
  • 发表于 2020-05-04 13:53
  • 阅读 ( 146 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除