Springboot整合thymeleaf实现国际化


知识概念

一、什么是Thymeleaf?

Thymeleaf是适用于web和独立环境的现代服务器端java模板引擎
Thymeleaf的主要目标是为您的开发工作流程带来优雅的自然模板 - 可以在浏览器中正确显示的HTML,也可以用作静态原型,从而在开发团队中实现更强大的协作。
借助Spring Framework的模块,与您喜欢的工具的大量集成,以及插入您自己的功能的能力,Thymeleaf是现代HTML5 JVM Web开发的理想选择 - 尽管它可以做得更多。
总之是为了在html动态能显示数据。

二、Html和Jsp的区别


Html:超文本标记语言,静态页面,可以直接被浏览器渲染成页面。html完美体现前后端模块分离,各司其职的属性,同时还减轻了服务器端的压力,但是会增加浏览器即客户端的压力。
Jsp:全称为java server page,需要服务器动态拼接页面后传递给浏览器,然后浏览器再渲染成页面。它是需要服务器进行一系列操作因此会增加服务器端的压力。

三、知识梳理








    如上图可知springboot框架默认的Local解析器为AcceptHeaderLocaleResolver,AcceptHeaderLocaleResolver又是根据Request Headers的accept-language的值来解析Local,并且是不可变的。那么想要实现国际化,就要使用SessionLocaleResolver或者CookieLocaleResolver。

四、示例

框架:Springboot;  (thymeleaf官方使用教程)
application.properties
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
spring.thymeleaf.cache=false
spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**  
Pom.xml
<dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-thymeleaf</artifactId>
   </dependency>
I18nConfig
@Configuration
public class I18nConfig {

    //定义资源位置及编码方式
    @Bean
    public ResourceBundleMessageSource  messageSource(){
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setBasename("static/i18n/message");
        messageSource.setDefaultEncoding("UTF-8");
        messageSource.setCacheSeconds(1);
        return messageSource;
    }
    //定义Local解析方式并设置默认为中文
    @Bean 
    public LocaleResolver localeResolver(){
        SessionLocaleResolver resolver = new SessionLocaleResolver();
        resolver.setDefaultLocale(Locale.CHINA);
        return resolver;
    }
}
资源文件位置如下图:

国际化切换
@RestController
@RequestMapping(value="/i18n")
public class InternationalController {

    @RequestMapping(value="/selectLanguage")
    public String selectLanguage(String language,HttpServletRequest request){
        Locale locale = null;
        if(language.equals("ENGLISH")){
            locale = new Locale("en", "US");
            request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, locale);
            request.getSession().setAttribute("lan", "en_US");
        }else{
            locale = new Locale("zh", "CN");
            request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, locale);
            request.getSession().setAttribute("lan", "zh_CN");
        }
        return "true";
    }

} 

三、总结

Springboot结合Thymeleaf实现国际化原理就是根据用户的需求动态的切换不同资源文件。与代码来说就是更换不同的Locale,不同的Locale,就从不同的资源文件中获取数据