springMVC国际化总结

 1.配置springMVC

<!-- 国际化 -->
	<bean id="messageSource"
		class="org.springframework.context.support.ResourceBundleMessageSource">
		<property name="cacheSeconds" value="5" />
		<!-- 资源刷新间隔时间 -->
		<property name="basenames">
			<list>
                <!-- 文件示例 -->
				<!-- /src/config/i18n/messages_en_US.properties -->
				<!-- /src/config/i18n/messages_zh_CN.properties -->
				<value>config.i18n.messages</value>
			</list>
		</property>
	</bean>

	<!-- 基于Session的国际化配置 -->
	<bean id="localeResolver"
		class="org.springframework.web.servlet.i18n.SessionLocaleResolver"></bean>

	<!-- 国际化操做 拦截器 必需配置,能够和其它国际化方式通用 -->
	<bean id="localeChangeInterceptor"
		class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />

2.controller 拦截

// 国际化配置语言
		if (langType.equals("zh")) {
			Locale locale = new Locale("zh", "CN");
			request.getSession()
					.setAttribute(
							SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,
							locale);
		} else if (langType.equals("en")) {
			Locale locale = new Locale("en", "US");
			request.getSession()
					.setAttribute(
							SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,
							locale);
		} else
			request.getSession().setAttribute(
					SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,
					LocaleContextHolder.getLocale());

3.freemarker页面的引用(jsp请自寻)

到org.springframework.web.servlet.view.freemarker目录下复制spring.ftl到相关目录(/WebRoot/WEB-INF/template/spring.ftl)java

在springMVC整合freemarker视图的配置中添加配置:自动引入spring的宏命令库。jquery

<prop key="auto_import">/template/spring.ftl as spring</prop>

完整的示例:web

<!-- freemarker视图 -->
	<!-- 必定要放在viewResolver的前面,这样就先去找freemarker的 -->
	<bean id="freemarkerConfig"
		class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
		<property name="templateLoaderPath" value="/WEB-INF/" />
		<property name="freemarkerSettings">
			<props>
				<!-- 编码 -->
				<prop key="defaultEncoding">UTF-8</prop>
				<!-- 国际化 -->
				<prop key="auto_import">/template/spring.ftl as spring</prop>
				<!-- 缓存刷新 -->
				<prop key="template_update_delay">0</prop>
				<!-- 数字逗号分隔 -->
				<prop key="number_format">0.##</prop>
				<!-- 日期格式化 -->
				<prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
				<!-- 变量null更换为空字符 -->
				<prop key="classic_compatible">true</prop>
			</props>
		</property>
	</bean>

提示:也能够本身手工引用 <#import "/common/spring.ftl" as spring/>spring

4.页面显示

<@spring.message "home"/> 其中home在国际化配置文件中配置。缓存

5.总结

作国际化有些麻烦的,除了页面上,还有我我的些一下js也要进行国际化,查了些资料,打算使用jquery-i18next,暂时先搁置着,有时间了在进行下一步的记录。jsp

相关文章
相关标签/搜索