javaweb简单实现国际化信息输出(参考)

2016/05/22 23:57
阅读数 332


使用spring自带的功能实现信息国际化输出,需要导入spring.jar文件

过程思路:

1、新建messages_zh_CN.properties中文属性配置文件(zh_CN代表中国大陆,一般格式都是固定的,默认在src目录)

      新建messages_en_US.properties英文属性配置文件(en_US代表美国)

2、新建类MessageBuilder.java信息读取类,主要用来提供方法供程序调用,输出需要打印出来的国际化信息。

主要通过加载xml配置信息使用spring的org.springframework.context.support.ResourceBundleMessageSource类来读取messages_zh_CN.properties等里面的内容

3、message-context.xml配置信息,主要用来被MessageBuilder加载使用

本人对spring框架源代码理解不多,现在主要是使用阶段,有很多东西我也不知道原理,只知道怎么来用。解释不清楚的地方望谅解,也可以回复讨论。


messages_zh_CN.properties(由于编码格式问题,我的中文字符显示为Unicode16编码,占2个字节,在编写国际化程序的时候会用到,如果显示的是汉字也是对的。

0000=\u6210\u529f{0}
0001=\u5931\u8D25{0}{1}
0002=\u4F60\u597D\u4E16\u754C
messages_en_US.properties

0000=success{0}
0001=fail{0}{1}
0002=hello world
message-context.xml配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
	<bean id="messageSource"  class="org.springframework.context.support.ResourceBundleMessageSource">  
      <property name="basename" value="messages"/>  
    </bean>  
</beans>

MessageBuilder:

package org.inout.example;

import java.util.Locale;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MessageBuilder {
    private static ApplicationContext context;//主要用来读取配置文件
    private static Locale defaultLocale = Locale.getDefault();//根据系统自定义地区
    
    public static String getMessage(String code,Object ... values){
        if(context == null){
            initialContext();
        }
        //message结果就是messages_en_US.properties里面对应的编号(code)对应值,values代表可以填充的信息,
        //例如:messages_en_US中定义0003=success{0}{1},values传入["AAA","BBB"],code传入0003,输出结果为successAAABBB
        String message = context.getMessage(code, values, defaultLocale);
        return message;
    }
    
    public static String getMessage(String code){
        return getMessage(code,new Object[]{});
    }
    /**
     * 初始化context,当有多个线程都加载MessageBuilder时为了安全需要加上synchronized
     */
    private static synchronized void initialContext() {
        if(context != null){
            return;
        }
        //message-context.xml默认在src下,也可以自己建立路径。例如(com/config/message-context.xml)
        context = new ClassPathXmlApplicationContext(
                new String[] {"message-context.xml"});
    }
    
}
测试类:使用junit测试,需要导入junit4的jar

package org.dyb.test;

import org.inout.example.MessageBuilder;
import org.junit.Test;
import com.sun.ejb.ejbql.parser.ParseException;

public class TestString {
    @Test
    public void test() throws ParseException{
        System.out.println(MessageBuilder.getMessage("0000","aaa"));
        System.out.println(MessageBuilder.getMessage("0001",new Object[]{"aaa","bbb"}));
        System.out.println(MessageBuilder.getMessage("0002"));
    }
}

输出结果:

成功aaa
失败aaabbb
你好世界

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
1 收藏
2
分享
返回顶部
顶部