zoukankan      html  css  js  c++  java
  • 4_3.springboot2.x之默认访问首页和国际化

    1、默认访问首页

    1.引入thymeleaf和引入bootstrap

    <!--引入thymeleaf-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-thymeleaf</artifactId>
            </dependency>
            <!--引入bootstrap-->
            <dependency>
                <groupId>org.webjars</groupId>
                <artifactId>bootstrap</artifactId>
                <version>4.1.0</version>
            </dependency>
    

    2.新建mvc配置类

    //@EnableWebMvc
    @Configuration//扩展springmvc功能
    public class MyMvcConfig implements WebMvcConfigurer {
          //用来做视图映射 浏览器发送 /和/index.htm 请求来到 login页面(由thymeleaf提供)
        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
            registry.addViewController("/").setViewName("login");
            registry.addViewController("/index.html").setViewName("login");
            registry.addViewController("/main.html").setViewName("dashboard");
        }
        
      
    }
    
    

    application.properties

    server.servlet.context-path=/crud 
    

    配置web应用的请求路径

    2、国际化

    springmvc国际化的配置:

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

    2)、使用ResourceBundleMessageSource管理国际化资源文件

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

    springboot自动化的配置:

    步骤:

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

    login.properties

    在这里插入图片描述
    login_en_US.properties

    log.btn=Sign In
    login.password=Password
    login.Remember=Remember me
    login.tip=Please sign in
    login.username=Username
    

    在这里插入图片描述

    中文环境类似

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

    @Configuration
    @ConditionalOnMissingBean(value = MessageSource.class, search = SearchStrategy.CURRENT)
    @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
    @Conditional(ResourceBundleCondition.class)
    @EnableConfigurationProperties
    public class MessageSourceAutoConfiguration {
        
        //添加基础名配置类,配置文件可以直接放在类路径下叫messages.properties;
        @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;
    	}
        
    }
    

    application.properties

    spring.messages.basename=i18n.login, i18n.language
    

    3)、去页面获取国际化的值

    由于使用thymeleaf,用#{}取国际化信息

    			<input type="text" name="username" class="form-control" placeholder="Username" th:placeholder="#{login.username}" required="" autofocus="">
    
    

    若这里有中文乱码,请参考idea中properties中文乱码怎么解决。

    效果:根据浏览器语言设置的信息切换了国际化;

    4)、点击链接切换国际化

    原理解析:

    springmvc中:国际化Locale(区域信息对象);LocaleResolver(获取区域信息对象);

    WebMvcAutoConfiguration

    @Bean
    		@ConditionalOnMissingBean
    		@ConditionalOnProperty(prefix = "spring.mvc", name = "locale")
    		public LocaleResolver localeResolver() {
    			if (this.mvcProperties.getLocaleResolver() == WebMvcProperties.LocaleResolver.FIXED) {
    				return new FixedLocaleResolver(this.mvcProperties.getLocale());
    			}
                //根据请求头request中获取区域信息,
    			AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
    			localeResolver.setDefaultLocale(this.mvcProperties.getLocale());
    			return localeResolver;
    		}
    

    自定义区域信息解析器:

    html页面:	
    <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>
    

    区域信息解析器:

    package com.spboot.springboot04.component;
    
    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 request) {
            String l = request.getParameter("l");
            Locale locale = Locale.getDefault();//根据浏览器默认
            if(!StringUtils.isEmpty(l)){
                String[] s = l.split("_");
                locale = new Locale(s[0],s[1]);
            }
            return locale;
        }
    
        @Override
        public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
    
        }
    }
    
    

    将自己添加的区域信息解析器添加到springmvc配置类中,从而添加到容器中:

    @Configuration//扩展springmvc功能
    public class MyMvcConfig implements WebMvcConfigurer {
       	   .
           .
           .
           .
         @Bean
        public LocaleResolver localeResolver(){
    
            return new MyLocaleResolver();
        }
    }
    

    测试:
    在这里插入图片描述

  • 相关阅读:
    leetcode:655. 输出二叉树
    leetcode:763. 划分字母区间
    leetcode:3. 无重复字符的最长子串
    leetcode:2. 两数相加
    leetcode每日一题:409. 最长回文串
    leetcode:1381. 设计一个支持增量操作的栈
    leetcode:1380. 矩阵中的幸运数
    [数据结构] 迷宫问题(栈和队列,深搜和广搜)
    [数据结构] N皇后问题
    [2011山东ACM省赛] Sequence (动态规划)
  • 原文地址:https://www.cnblogs.com/jatpeo/p/11767484.html
Copyright © 2011-2022 走看看