• 11、springboot——CRUD国际化②


    以前使用springmvc国际化步骤

    1)、编写国际化配置文件;

    2)、使用ResourceBundleMessageSource管理国际化资源文件
    3)、在页面使用fmt:message取出国际化内容

    springboot国际化步骤:

     步骤:

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

    在编写国际化文件前先确定文件的编码统一为utf-8

    创建国际化文件

    文件内容:

     在全局配置文件中配置自定义的国际化文件路径

    2)、使用thymeleaf的语法(使用#{})去引用(以前jsp是用fmt)

    复制代码
    <form class="form-signin" action="dashboard.html">
       <img class="mb-4" src="asserts/img/bootstrap-solid.svg" alt="" width="72" height="72">
       <h1 class="h3 mb-3 font-weight-normal" th:text="#{index_top}">Please sign in</h1>
       <label class="sr-only">Username</label>
       <input type="text" class="form-control" th:placeholder="#{index_Username}" placeholder="Username" required="" autofocus="">
       <label class="sr-only">Password</label>
       <input type="password" class="form-control" th:placeholder="#{index_password}" placeholder="Password" required="">
       <div class="checkbox mb-3">
          <label>
            <input type="checkbox" value="remember-me"> [[#{index_rember}]]
          </label>
       </div>
       <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
       <p class="mt-5 mb-3 text-muted">© 2017-2018</p>
       <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>
    </form>
    复制代码

    效果是根据浏览器的语言设置进行国际化的显示

    3)运行查看

    系统为英文

    系统语言选择中文:

    SpringBoot自动配置好了管理国际化资源文件的组件

     

    复制代码
    @Configuration
    @ConditionalOnMissingBean(
        value = {MessageSource.class},
        search = SearchStrategy.CURRENT
    )
    @AutoConfigureOrder(-2147483648)
    @Conditional({MessageSourceAutoConfiguration.ResourceBundleCondition.class})
    @EnableConfigurationProperties
    public class MessageSourceAutoConfiguration {
        private static final Resource[] NO_RESOURCES = new Resource[0];
    
        public MessageSourceAutoConfiguration() {
        }
    
        @Bean
        @ConfigurationProperties(
            prefix = "spring.messages"
        )
        public MessageSourceProperties messageSourceProperties() {
            return new MessageSourceProperties();
        }
    
        @Bean
        public MessageSource messageSource(MessageSourceProperties properties) {
            //管理国际化的
            ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
            if (StringUtils.hasText(properties.getBasename())) {
                ////设置国际化资源文件的基础名(去掉语言国家代码的)
                messageSource.setBasenames(StringUtils.commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(properties.getBasename())));
            }
    
            if (properties.getEncoding() != null) {
                messageSource.setDefaultEncoding(properties.getEncoding().name());
            }
    
            messageSource.setFallbackToSystemLocale(properties.isFallbackToSystemLocale());
            Duration cacheDuration = properties.getCacheDuration();
            if (cacheDuration != null) {
                messageSource.setCacheMillis(cacheDuration.toMillis());
            }
    
            messageSource.setAlwaysUseMessageFormat(properties.isAlwaysUseMessageFormat());
            messageSource.setUseCodeAsDefaultMessage(properties.isUseCodeAsDefaultMessage());
            return messageSource;
        }
    
        protected static class ResourceBundleCondition extends SpringBootCondition {
            private static ConcurrentReferenceHashMap<String, ConditionOutcome> cache = new ConcurrentReferenceHashMap();
    
            protected ResourceBundleCondition() {
            }
    
            public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
                ////我们的配置文件可以直接放在类路径下叫messages.properties
                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;
            }
    
            private ConditionOutcome getMatchOutcomeForBasename(ConditionContext context, String basename) {
                Builder message = ConditionMessage.forCondition("ResourceBundle", new Object[0]);
                String[] var4 = StringUtils.commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(basename));
                int var5 = var4.length;
    
                for(int var6 = 0; var6 < var5; ++var6) {
                    String name = var4[var6];
                    Resource[] var8 = this.getResources(context.getClassLoader(), name);
                    int var9 = var8.length;
    
                    for(int var10 = 0; var10 < var9; ++var10) {
                        Resource resource = var8[var10];
                        if (resource.exists()) {
                            return ConditionOutcome.match(message.found("bundle").items(new Object[]{resource}));
                        }
                    }
                }
                return ConditionOutcome.noMatch(message.didNotFind("bundle with basename " + basename).atAll());
            }
            private Resource[] getResources(ClassLoader classLoader, String name) {
                String target = name.replace('.', '/');
    
                try {
                    return (new PathMatchingResourcePatternResolver(classLoader)).getResources("classpath*:" + target + ".properties");
                } catch (Exception var5) {
                    return MessageSourceAutoConfiguration.NO_RESOURCES;
                }
            }
        }
    }
    复制代码

     

    容器中没有就使用默认的

    复制代码
    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnProperty(
        prefix = "spring.mvc",
        name = {"locale"}
    )
    public LocaleResolver localeResolver() {
        if (this.mvcProperties.getLocaleResolver() == org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties.LocaleResolver.FIXED) {
            return new FixedLocaleResolver(this.mvcProperties.getLocale());
        } else {
            AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
            localeResolver.setDefaultLocale(this.mvcProperties.getLocale());
            return localeResolver;
        }
    }
    复制代码

     原理:

    国际化的Local(区域信息对象);LocalResolver(获取区域信息对象)

    自定义LocalResolver

    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 l = httpServletRequest.getParameter("l");    //获取传入的参数l
            Locale locale = java.util.Locale.getDefault();         //默认使用系统默认的
            if(!StringUtils.isEmpty(l)){
                String[] split =  l.split("_");             //参数不为空则以参数中的信息为准
                locale = new Locale(split[0],split[1]);
            }
            return locale;
        }
    
        @Override
        public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
    
        }
    }

    加入容器

    @Bean(name="localeResolver")
    public LocaleResolver MyLocaleResolver(){
        return  new MyLocaleResolver();
    }

     值得一说的是

    @Bean()
    public LocaleResolver localeResolver(){
        return  new MyLocaleResolver();
    }

     LocaleResolver 如果后面不跟localeResolver的话  就需在@Bean指定name

     页面中链接中加入参数

     

    点击即可进行切换

  • 相关阅读:
    测试报告M2
    11.24Daily Scrum(4)
    11.24Daily Scrum(3)
    11.24Daily Scrum(2)
    11.24Daily Scrum
    11.22Daily Scrum(2)
    11.22Daily Scrum
    Echarts中graph类型的运用求教
    Echarts学习求教
    用node编写自己的cli工具
  • 原文地址:https://www.cnblogs.com/lyh233/p/12519513.html
Copyright © 2020-2023  润新知