一闹丐、在頁(yè)面上能夠根據(jù)瀏覽器語(yǔ)言設(shè)置的情況對(duì)文本(不是內(nèi)容)阱高、時(shí)間赚导、數(shù)值進(jìn)行本地化處理。解決方法是通過(guò)使用 JSTL 的 fmt 標(biāo)簽赤惊。
如果使用了JSTL 的 fmt 標(biāo)簽吼旧,需要在SpringMVC 的配置文件中配置國(guó)際化資源文件∥粗郏可以根據(jù)瀏覽器選擇的語(yǔ)言不通圈暗,讀取不同的國(guó)際資源屬性文件。(處于不同國(guó)家時(shí)裕膀,瀏覽器語(yǔ)言不同)
<!-- 配置國(guó)際化資源文件? -->
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="i18n"></property>
</bean>
在 src 目錄下员串,創(chuàng)建名為 i18n.properties 的文件。內(nèi)容如下:
然后在 src 目錄下創(chuàng)建中文和美國(guó)對(duì)應(yīng)的 i18n.properties 文件昼扛,i18n_zh_CN.properties(中國(guó))寸齐,內(nèi)容分別為中文的 用戶(hù)名 和 密碼,
i18n_en_US.properties(美國(guó))。
接著在 請(qǐng)求界面寫(xiě)一個(gè)鏈接:
<a href="/SpringMVC_3/testModelAndView">testModelAndView</a>
在 Controller 類(lèi)中寫(xiě)一個(gè)方法:
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView(){
ModelAndView mav = new ModelAndView(success);
return mav;
}
在顯示界面顯示:(首先需要在界面中引入 fmt 標(biāo)簽)
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
在 HTML 中的 body 中寫(xiě)入:
<fmt:message key="i18n.username"></fmt:message></br>
<fmt:message key="i18n.password"></fmt:message></br>
運(yùn)行項(xiàng)目后顯示如圖:
選擇瀏覽器的 Internet 選項(xiàng)--語(yǔ)言選項(xiàng)渺鹦,找到 英語(yǔ)(美國(guó))扰法,添加,設(shè)為首選毅厚。刷新界面塞颁。
二、在 bean 中獲取國(guó)際化資源文件 local 對(duì)應(yīng)的消息吸耿,解決方法是在 bean 中注入 ResourceBundleMessageSource ?的實(shí)例祠锣,調(diào)用其 getMessage()方法即可。
注解掉步驟一中的通過(guò)視圖名直接響應(yīng)珍语。
<!-- <mvc:view-controller path="/i18n" view-name="i18n"/> -->
請(qǐng)求界面鏈接:
<a href="/SpringMVC_3/i18n">test i18n</a>
在 Handler(Controller)中寫(xiě)一個(gè)響應(yīng)方法锤岸。
@Autowired
//注入 ResourceBundleMessageSource的實(shí)例
private ResourceBundleMessageSource messageSource;?
@RequestMapping("/i18n")
public String testI18n(Locale locale){
//調(diào)用 getMessage方法獲取 i18n.username 的值,輸出
String val = messageSource.getMessage("i18n.username", null, locale);
System.out.println(val);
return "i18n";
}?
響應(yīng)界面 i18n.jsp 顯示信息:(首先需要在界面中引入 fmt 標(biāo)簽)
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
在 HTML 中的 body 中寫(xiě)入:
<fmt:message key="i18n.username"></fmt:message>
<fmt:message key="i18n.password"></fmt:message>
三板乙、通過(guò)超鏈接切換 local 是偷,而不再依賴(lài)與瀏覽器語(yǔ)言設(shè)置情況。解決方法是配置 LocaleResolver 和 LocaleChangeInterceptor募逞。
在 mvc 的配置文件中配置 LocaleResolver 和 LocaleChangeInterceptor蛋铆。
<!-- 配置SessionLocalResolver? -->
<bean id="localeResolver "
class="org.springframework.web.servlet.i18n.SessionLocaleResolver ">
</bean>
<!-- 配置LocaleChangeInterceptor -->
<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"></bean>
</mvc:interceptors>
請(qǐng)求界面鏈接:
<a href="/SpringMVC_3/i18n?local=zh_CN">中文</a>
<a href="/SpringMVC_3/i18n?local=en_US">英文</a>