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();
    }
}

測試:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章