close
Spring Boot + Freemarker 多語言國際化的作法
1. 在 application.properties 增加
# =============================== # Multi Language # =============================== spring.messages.basename=i18n/messages # 為了取得當前頁面的URL (get current page url) spring.freemarker.expose-spring-macro-helpers=true
2. 在 resource 目錄下建立一個目錄 i18n , 並新增三個檔
messages.properties , messages_zh_TW.properties , 內容為
label.login = 登入
messages_en_US.properties 內容為
label.login = Login
3. 建立 WebMvcConfig : MvcConfig.class
@Configuration public class MvcConfig implements WebMvcConfigurer { //多語系設定 @Bean(name = "localeResolver") public LocaleResolver getLocaleResolver() { CookieLocaleResolver resolver= new CookieLocaleResolver(); resolver.setCookieDomain("jwtLocaleCookie"); // 60 minutes resolver.setCookieMaxAge(60*60); return resolver; } //多語系設定 語系切換偵測 @Override public void addInterceptors(InterceptorRegistry registry) { LocaleChangeInterceptor localeInterceptor = new LocaleChangeInterceptor(); localeInterceptor.setParamName("lang"); registry.addInterceptor(localeInterceptor).addPathPatterns("/*"); } }
4. Control file: MainController.class
@Controller public class MainController { @RequestMapping(value = { "/","/home" }) public String staticResource(Model model) { return "home"; } }
5. View: home.ftl
<#import "/spring.ftl" as spring/>
<@spring.message "label.login"/>
注意, FTL的第一行要 import "/spring.ftl" ,這樣子就可以輕鬆切換語系了
文章標籤
全站熱搜
留言列表