用spring boot,加thymeleaf模板引擎开发网站,很强。
记一些关键点。
一.搞多国语言 i18n
1.把这些豆类加进去:
//i18n,默认设为中文 @Bean public LocaleResolver localeResolver() { CookieLocaleResolver clr = new CookieLocaleResolver();//also can use SessionLocaleResolver clr.setDefaultLocale(Locale.SIMPLIFIED_CHINESE); return clr; } //i18n,用?lang=en切换语言 @Bean public LocaleChangeInterceptor localeChangeInterceptor() { LocaleChangeInterceptor lci = new LocaleChangeInterceptor(); lci.setParamName("lang"); return lci; } //i18n,把上面那个加进Interceptors里 @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(localeChangeInterceptor()); }
2.在resources里加这些文件:
messages.propertiesmessages_en.propertiesmessages_jp.properties
这些文件的格式为:
testpage.input2number_then_press_submit=输入两个数字,点提交 testpage.submit=提交 submit=提交 user.username=账号
. 3.给html加一些切换按钮(thymeleaf模板引擎的写法)
<a th:text="西恩" th:href="@{'?lang=CN'}">CN</a> <a th:text="English" th:href="@{'?lang=en'}">en</a> <a th:text="日本語" th:href="@{'?lang=jp'}">jp</a>
4.在html中加入这些多国语言字符串,用#{}表示
<p th:text="#{testpage.input2number_then_press_submit}">#{testpage.input2number_submit}</p> <form action="/testAction"> <input name="numA"/> <input name="numB"/> <button type="submit" th:text="#{testpage.submit}">submit</button> </form>
5.完成!但是这里面我遇到一个奇怪问题,至今没有解决。
在windows下,如果某个语言没有语句A的翻译,那会用默认的messages.properties里的语句A。但是到linux服务器下运行,它会用messages_en里的语句A,卧槽,为什么。我现在只有先不管这个问题了,影响不大。谁知道怎么解决或者这个问题的issue要去哪里提交的,告诉我一下……