史上最简单的springboot国际化多语言切换实现方案

 

每天学习一点点 编程PDF电子书、视频教程免费下载:
http://www.shitanlife.com/code

 

前提:

在resources目录下建立 messages_en_US.properties、messages_zh_CN.properties语言配置文件。

定义变量,如下: school_cover_title = School Cover

 

实现:

1. 启动文件中代码如下配置:

public class TwSpringCloudBigScreenWebApplication extends WebMvcConfigurerAdapter
{

    public static void main(String[] args)
    {
        TimeZone.setDefault(TimeZone.getTimeZone("GMT+8"));
        SpringApplication.run(TwSpringCloudBigScreenWebApplication.class, args);
    }
    
    @Bean  
    public LocaleResolver localeResolver() {  
        SessionLocaleResolver slr = new SessionLocaleResolver();  
        slr.setDefaultLocale(Locale.SIMPLIFIED_CHINESE);  
        return slr;  
    }  
  
    @Bean  
    public LocaleChangeInterceptor localeChangeInterceptor() {  
        LocaleChangeInterceptor lci = new LocaleChangeInterceptor();  
        lci.setParamName("lang");  
        return lci;  
    }  
  
    @Override  
    public void addInterceptors(InterceptorRegistry registry) {  
        registry.addInterceptor(localeChangeInterceptor());  
    }  
}

 

 

2. Controller 类中定义请求响应

    @RequestMapping(value={"", "/", "/index"}, method = RequestMethod.GET)
    public String index(ModelMap model)
    {
        if(null == chinaMapUrl || chinaMapUrl.length() == 0)
        {
            chinaMapUrl = "http://218.77.50.45:8222/showroom/front/first/map_pass";
        } 
        model.addAttribute("chinaMapUrl",chinaMapUrl); 
        return "index";
    }

 

3. index.html静态页面中定义切换按钮

<a href="?lang=en_US" > 英语</a>  
<a href="?lang=zh_CN" > 中文</a>  

 

 

实现以上三步,即可实现语言切换。

 

 

 

 

每天学习一点点 编程PDF电子书、视频教程免费下载:
http://www.shitanlife.com/code

posted @ 2018-05-17 11:49  漫步CODE人生  阅读(26061)  评论(0编辑  收藏  举报