美文网首页
SpringBoot 国际化

SpringBoot 国际化

作者: 拉提娜的爸爸 | 来源:发表于2019-09-29 09:11 被阅读0次

    1、根据浏览器语言设置的信息切换了国际化

    1)编写国际化配置文件,抽取页面需要显示的国际化消息

    编写国际化配置文件
    抽取页面需要显示的国际化消息,并配置
    2)使用ResourceBundleMessageSource管理国际化资源文件
    • 在application.properties配置文件中,添加国际化配置文件路径,使其生效
    # 页面国际化配置,路径如步骤1的图片所示
    spring.messages.basename=i18n.login
    
    • SpringBoot自动配置好了管理国际化资源文件的组件;
    ConfigurationProperties(prefix="spring.messages") publicclassMessageSourceAutoConfiguration{
        /**
         * Comma‐separated list of basenames (essentially a fully‐qualified classpath
         * location), each following the ResourceBundle convention with relaxed support for
         * slash based locations. If it doesn't contain a package qualifier (such as
         * "org.mypackage"), it will be resolved from the classpath root.
         */
    private String basename = "messages"; //我们的配置文件可以直接放在类路径下叫messages.properties;
        @Bean
        public MessageSource messageSource() {
            ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
            if (StringUtils.hasText(this.basename)) {
                //设置国际化资源文件的基础名(去掉语言国家代码的) messageSource.setBasenames(StringUtils.commaDelimitedListToStringArray(
                StringUtils.trimAllWhitespace(this.basename)));
            }
            if (this.encoding != null) {
                messageSource.setDefaultEncoding(this.encoding.name());
            }
            messageSource.setFallbackToSystemLocale(this.fallbackToSystemLocale);
            messageSource.setCacheSeconds(this.cacheSeconds);
            messageSource.setAlwaysUseMessageFormat(this.alwaysUseMessageFormat);
            return messageSource;
    }
    

    3)在页面使用fmt:message取出国际化内容

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
            <meta name="description" content="">
            <meta name="author" content="">
            <title>Signin Template for Bootstrap</title>
            <!-- Bootstrap core CSS href="asserts/css/bootstrap.min.css"-->
            <link  th:href="@{/webjars/bootstrap/4.3.1/css/bootstrap.css}" rel="stylesheet">
            <!-- Custom styles for this template href="asserts/css/signin.css"-->
            <link  th:href="@{/asserts/css/signin.css}" rel="stylesheet">
        </head>
    
        <body class="text-center">
            <form class="form-signin" action="dashboard.html">
                <!--src="asserts/img/bootstrap-solid.svg"-->
                <img class="mb-4" th:src="@{/asserts/img/bootstrap-solid.svg}" alt="" width="72" height="72">
                <h1 class="h3 mb-3 font-weight-normal" th:text="#{login.top}">Please sign in</h1>
                <label class="sr-only" th:text="#{login.username}">Username</label>
                <input type="text" class="form-control" placeholder="Username" th:placeholder="#{login.username}" required="" autofocus="">
                <label class="sr-only" th:text="#{login.password}">Password</label>
                <input type="password" class="form-control" placeholder="Password" th:placeholder="#{login.password}" required="">
                <div class="checkbox mb-3">
                    <label>
              <input type="checkbox" value="remember-me"> [[#{login.remember}]]
            </label>
                </div>
                <button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.btn}">Sign in</button>
                <p class="mt-5 mb-3 text-muted">© 2017-2018</p>
                <a class="btn btn-sm">中文</a>
                <a class="btn btn-sm">English</a>
            </form>
        </body>
    </html>
    

    2、点击链接切换国际化

    1)编写国际化配置文件,抽取页面需要显示的国际化消息
    同上
    2)给中英文选择加链接

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

    th:href="@{/index.html(l='zh_CN')}说明:
    /index.html:访问页面的路径
    l='zh_CN':国际化的参数,带不带引号都可以
    3)配置国际化代码

    package com.mystudy.springboot.config;
    
    
    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 {
    
        @Override
        public Locale resolveLocale(HttpServletRequest httpServletRequest) {
            String parameter = httpServletRequest.getParameter("l");
            //如果为空,返回默认信息
            Locale locale = Locale.getDefault();
            if(!StringUtils.isEmpty(parameter)){
                String[] split = parameter.split("_");
                locale = new Locale(split[0],split[1]);
            }
            return locale;
        }
    
        @Override
        public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
    
        }
    }
    
    

    将写好的配置代码加入容器中

    package com.mystudy.springboot.config;
    
    import com.mystudy.springboot.interceptor.LoginInterceptor;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.LocaleResolver;
    import org.springframework.web.servlet.config.annotation.*;
    
    @Configuration
    public class MyMvcConfig implements WebMvcConfigurer {
    
        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
            registry.addViewController("/").setViewName("login");
            registry.addViewController("/index.html").setViewName("login");
        }
    
    //    @Override
    //    public void addInterceptors(InterceptorRegistry registry) {
    //        // 注册拦截器
    //        InterceptorRegistration addInterceptor = registry.addInterceptor(new LoginInterceptor());
    //        // 配置拦截器路径
    //        addInterceptor.addPathPatterns("/**");
    //        // 配置不拦截路径
    //        addInterceptor.excludePathPatterns("/login","/","/index.html");
    //
    //    }
        // 将国际化配置加入到容器中,当有手动加入的配置时,SpringBoot默认的国际化配置将不再生效
        @Bean
        public LocaleResolver localeResolver(){
            return new MyLocaleResolver();
        }
    }
    
    

    相关文章

      网友评论

          本文标题:SpringBoot 国际化

          本文链接:https://www.haomeiwen.com/subject/mfzfyctx.html