Java系列--第六篇 基于Maven的SSME之多国语言实现

如果你的网站足够强大,以致冲出了国门,走向了国际的话,你就需要考虑做多国语言了,不过,未雨绸缪,向来是我辈程序人员的优秀品质,谁知道那天,我们的网站被国外大公司看中收购,从而飞上枝头变凤凰。不扯这么多,还是看看我是如何在ssme里面实现多国语言吧。这可是我从我们实际项目中剥离出来的一手资料呢。

1, 新建properties文件,index_en_US.properties和index_zh_CN.properties

<?xml version="1.0" encoding="UTF-8"?>
message.greeting=Hello {0}, your email is {1}
i18n/index_en_US.properties
<?xml version="1.0" encoding="UTF-8"?>
message.greeting=您好 {0}, 您的邮件地址是 {1}
i18n/index_zh_CN.properties

2, 配置spring-mvc.xml ,使用org.springframework.context.support.ReloadableResourceBundleMessageSource来定义messageSource. 用org.springframework.web.servlet.i18n.LocaleChangeInterceptor去拦截用户改变的locale. 用org.springframework.web.servlet.i18n.CookieLocaleResolver来保存用户的locale.

    <!-- 多国语言配置功能 -->
    <bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basenames">
            <list>
                <value>classpath:i18n/index</value>
            </list>
        </property>    
        <property name="defaultEncoding" value="UTF-8"/>
    </bean>
 
    <bean id="localeChangeInterceptor"
        class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
        <property name="paramName" value="lang" />
    </bean>
 
    <bean id="localeResolver"
        class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
        <property name="defaultLocale" value="en_US"/>
    </bean>
 
    <bean id="handlerMapping"
        class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
        <property name="interceptors">
            <ref bean="localeChangeInterceptor" />
        </property>
    </bean>
多国语言配置功能

3, 更改jsp文件,采用spring 标签来更做。更显国际范儿。要使用jsp的表达式,需要引用spring-expression3.2.4-RELEASE

<dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-expression</artifactId>
        <version>3.2.4.RELEASE</version>
</dependency>
spring-expression3.2.4.RELEASE

jsp头项入

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>

<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
注意pageEncoding="utf-8"

将原来的直接写在<h2>里面的语句改成

<spring:message code="message.greeting" arguments="${user.name},${user.email}"/>
带arguments的spring:message

为了让用户可以更改语言,所以在layout.tag的<head>里面加上

    <span style="float: right">
        <a href="?lang=en_US">English</a> 
        | 
        <a href="?lang=zh_CN">中文</a>
    </span>
span_float:right

可以看到,当用户单击a标签时,会加入一个参数?lang="",跟踪可以看到LocaleChangeInterceptor会截获这个请求的,因为我们带了lang参数。如果你觉得lang不喜欢,那么看到这里没

<property name="paramName" value="lang" />

改成你喜欢的value值即可。

最后运行程序,应该可以看到功能已经实现,由于代码实在比较简单,而且我都已贴上来了,所以源码就不上传了。贴个图来表示一下有图有真相。

http://images.cnblogs.com/cnblogs_com/SLKnate/515382/o_java_localization.png

原文地址:https://www.cnblogs.com/SLKnate/p/Java_Serial_SSME_Localized.html