SpringMVC + FreeMarker 國際化使用方法
1、配置Spring
<!-- 國際化 -->
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>i18n</value>
</list>
</property>
</bean>
2、建立資源文件
圖中使用了2組資源文件 i18n 與 messages,是爲了測試命名規則,因爲網上查資料看到有人講Spring國際化需要命名爲messages,結果這種說法完全錯誤。
文件前綴命名沒有限制,只需要與第一步中的value值匹配即可。後綴則必須按規則來寫messages_en_US.properties或i18n_en_US.properties。
3、項目中加入springmvc整合freemarker的國際化的支持文件spring.ftl,此文件在spring-webmvc的jar包中,以spring3.2爲例:
路徑爲:spring-webmvc-3.2.0.M1.jar\org\springframework\web\servlet\view\freemarker。將文件複製到項目中,方便引用
4、在freemarker文件中引入spring.ftl,即可獲取資源文件中的信息
圖中ProjectName即對應資源文件中的key值
5、加入配置可通過session控制國際化語言
<!-- 國際化操作 攔截器 -->
<bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
<!-- 基於Session的國際化配置 -->
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"></bean>
代碼中即可通過以下方法進行語言設置
request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, new Locale("zh", "CN"));
----------------------------END--------------------------