springMVC 国际化 多语言

来源:互联网 发布:怎么把照片上传到淘宝 编辑:程序博客网 时间:2024/06/17 09:14

springMVC 国际化(多语言) 配置


系统有时需要考虑多国人员使用(比如中国人、美国人、日本人、韩国人),面向不同国家的使用者应该能方便地在不同语言之间进行切换,比如中文、英文、日文、韩文。

常用的有两种方式:(1)根据浏览器默认语言设置系统语言;   (2)根据页面连接手动选择系统语言(放入cookie);

还有session方式,没有细究。


一、两种方式设置的大概模样:

(1)浏览器设置


(2)页面连接设置


二、添加多语言支持

1、添加多语言文件*.properties

label文件:languages_zh.properties、languages_en.properties、languages_ja.properties;

message文件:messages_zh.properties、messages_en.properties、messages_jp.properties;

文件内容以键值对表示,如:user=User、user=\u7528\u6237\u540D、user=\u30E6\u30FC\u30B6\u30FC;

在properties文件中中文日文等英文以外的语言显示unicode编码。

unicode编码看起来确实有些不爽,现在也有好的解决方式,比如如下连接中的博文介绍:点击打开链接


2、springMVC配置文件:我的文件名是spring-mvc.xml

    <!-- 配置国际化资源文件 -->    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">    <property name="basenames">    <list>    <value>messages</value>    <value>languages</value>    </list>    </property>    </bean>    <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver"> <property name="cookieMaxAge" value="604800"/> <property name="defaultLocale" value="zh_CN"/> <property name="cookieName" value="Language"></property>     </bean>

3、页面文件中添加jstl标签支持:

    <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>


4、页面使用多语言标签:

     <label><fmt:message key="user"></fmt:message>:</label> 


5、根据浏览器选择语言的场合,以上处理就OK了。在页面手动选择语言的场合,继续后面的操作:

(1)controller文件中添加RequestMapping

    /**     * 国际化设定     * @date 2017/09     * @param request     * @param response     * @throws Exception     */    @RequestMapping(value="/setLocal")    public void setLocal(HttpServletRequest request,HttpServletResponse response) throws Exception{       String localType = request.getParameter("localType");       if(localType.equals("zh")){           resolver.setLocale(request, response, Locale.CHINA);       }else if(localType.equals("en")){           resolver.setLocale(request, response, Locale.ENGLISH);       }else {            resolver.setLocale(request, response, Locale.JAPAN);        }    }

(2)登录添加链接,并使链接请求上面controller中的处理:

        <div><a href="javascript:void(0)" onclick="setLocal('zh')"><fmt:message key="l.Chinese"></fmt:message></a><a href="javascript:void(0)" onclick="setLocal('en')"><fmt:message key="l.English"></fmt:message></a><a href="javascript:void(0)" onclick="setLocal('ja')"><fmt:message key="l.Japanese"></fmt:message></a></div>

       <script type="text/javascript">function setLocal(local){  $.post(ctx+"/setLocal",{localType:local},function(result){  location.reload();  });}</script>

以上!

原创粉丝点击