SpringBoot 國際化LocaleContextHolder的基本配置


  1. 在resources創建文件

    messages_zh_CN.properties(中文),寫入

    #Unicode轉碼
    hello=\u4f60\u597D
    

    messages_en_US.properties(英文),寫入

    hello=hello world
    

    結構如圖在這里插入圖片描述

  2. 創建配置類

    @Configuration
    @EnableAutoConfiguration
    @ComponentScan
    public class LocaleConfig implements WebMvcConfigurer {
    
        //Cookie
        @Bean
        public LocaleResolver localeResolver() {
            CookieLocaleResolver localeResolver = new CookieLocaleResolver();
            localeResolver.setCookieName("localeCookie");
            //設置默認區域
            localeResolver.setDefaultLocale(Locale.ENGLISH);
            //設置cookie有效期.
            localeResolver.setCookieMaxAge(3600);
            return localeResolver;
        }
    
        @Bean
        public LocaleChangeInterceptor localeChangeInterceptor() {
            LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
            // 參數名
            lci.setParamName("lang");
            return lci;
        }
    
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(localeChangeInterceptor());
        }
    
    }
    
  3. 測試

    @RestController
    public class TestController {
    
        @Autowired
        private MessageSource messageSource;
    
        @GetMapping(path = "/test2",produces = "text/html;charset=utf-8")
        public Object test2(){
            Locale locale = LocaleContextHolder.getLocale();
            String hello = messageSource.getMessage("hello", null, locale);
            return hello;
        }
        
    }
    

    訪問
    http://127.0.0.1:8080/test2?lang=zh_CN
    http://127.0.0.1:8080/test2?lang=en_US


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM