`
wu-yansheng
  • 浏览: 15745 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

系统国际化1

阅读更多
对于稍微大一点的系统,国际化都是一个必须的步骤,很多系统为了不同的语言,做出了不同的页面甚至程序来支持,然后,对于.net或java相对成熟的平台下面,我们大可以利用已有的一些框架支持,来轻松的实现国际化的支持,下面我们以Spring为例子大致讲解一下如何利用已有框架简单的做到国际化的支持,我们简单的拿一个欢迎语句的中英文版本来做处理:
1、资源文件的编写:
英文版本资源文件,新建resource\user_en_US.properties,在资源文件中编写:
welcome.label=welcome {0} :time {1}
中文版本资源文件,新建resource\user_zh_CN.properties,在资源文件中编写:
welcome.label=欢迎你 {0} :时间 {1}
2、使用org.springframework.context.support.ResourceBundleMessageSource来配置messageSource(该名称为Spring约定):
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
	  <property name="basenames">
	     <list>
	       <value>user</value>	     
	     </list>
	  </property>
</bean>

3、现在,我们可以写测试类,说明如何使用国际化了:
public class testStation {

    /**
     * @param args
     */
    public static void main(String[] args) {
        ApplicationContext ctx = new
        FileSystemXmlApplicationContext("src/com/cun/resource/applicationContext.xml");       
        try {          
           Object[] obj=new Object[]{"wuyansheng",new Date()};  
           System.out.println(ctx.getMessage("welcome.label",obj, Locale.CHINA));  
           System.out.println(ctx.getMessage("welcome.label",obj, Locale.US));
          
          
       } catch (Exception e) {    
          System.out.println(e.getMessage());
       }       

    }
}

结果输出如下:
欢迎你 wuyansheng :时间 11-2-24 下午2:11
welcome wuyansheng :time 2/24/11 2:11 PM
即根据不同的本地语言环境,输出不同的信息。
4、怎么让异常信息也国际化呢,例如我们可以在页面的BaseAction中处理异常信息的国际化:
/**
	 * @return spring 上下文
	 */
	protected ApplicationContext getAppCtx(){
		return WebApplicationContextUtils.getWebApplicationContext(getSession()
				.getServletContext());
	}
	
	/**
	 * 获取资源信息
	 * @param key
	 * @param args
	 * @return
	 */
	public String getText(BaseException e){
		String key = e.getKey();
		String msg = super.getText(key, null, e.getParams());//本身Action是否配置了错误信息,
		if(msg != null) return msg;
		return getAppCtx().getMessage(key, e.getParams(), key, getLocale());
	}

这样在子类getText,传进具体的异常类,取出相应的异常信息。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics