07-06
19

MessageFormat和复合消息 (Bundle)

package domain.bean;

import java.util.ResourceBundle;
import java.text.MessageFormat;

public class FormatExample {
    public static void main(String[] args) {
        java.util.ResourceBundle bundle = ResourceBundle.getBundle(
                "ApplicationResources");//读取资源文件

        String errorsRequired = bundle.getString("errors.required");//找寻Key,返回valuve
        //{0}不能为空.
        String[] messages = new String[1]; //做一个数组

        messages[0] = bundle.getString("lable.name.error");//把String[0]的位置替换成部分消息,这里是"域名"
        MessageFormat messageFormat = null;//初始化MessageFormat类

        String MessageFormat = messageFormat.format(errorsRequired, messages);//格式化成复合消息

        System.out.println(MessageFormat);//打印:域名不能为空.
    }
}


上面这是一段孙卫琴书上的例子.
    
      下面我用MessageFormat类来做另外用途的实现,比如说之前曾写过的数据库连接的例子,现在改写下:

//JBDC直连
        try {
            /**
           java.util.ResourceBundle bundle = ResourceBundle.getBundle(
                "ApplicationResources_db");//读取资源文件

            String JDBCmysql=bundle.getString("JDBC.mysql.Driver");

            String URLJDBC=bundle.getString("JDBC.URL");

            String dbusername=bundle.getString("db.username");

            String dbpassword=bundle.getString("db.password");
             Class.forName(JDBCmysq).newInstance();//装载驱动
                         Connection conn=
             java.sql.DriverManager.getConnection(URLJDBC,dbusername,dbpassword);
             Statement stmt=conn.createStatement();//创建Statement,用于执行SQL
             ResultSet rs=stmt.executeQuery(sql);//调用executeQuery()取得结果集
                         while(rs.next())
                         {
                String name=rs.getString("name");
                //....
                         }
             **/
            String JNDI=bundle.getString("JNDI.DB");
            ///从数据源获得连接///假设server.xml//web.xml配置完毕
            Context initCtx = new javax.naming.InitialContext(); //初始化上下文
            DataSource ds = (DataSource) envCtx.lookup(JNDI); //查找数据源
            Connection conn = ds.getConnection();
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);


资源文件ApplicationResources_db.properties:
JDBC.mysql.Driver=org.gjt.mm.mysql.Driver
JDBC.URL=jdbc:mysql://127.0.0.1
db.username=root
dbpassword=
JNDI.DB=java:comp/env/jdbc/bn


       从上述代码不难看出,我把关于数据库连接的相关信息都提取到了一个资源文件(ApplicationResources_db.properties)中,到时取相应的valuve。这样的好处:开发阶段的数据库可能和运行阶段使用的数据库不一致。如不一致,在后期再重改源文件再进行编译显然很麻烦,而写在资源文件中,更改不用重新编译。

文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags: 国际化
相关日志:
评论: 0 | 引用: 0 | 查看次数: 659
发表评论
昵 称:
密 码: 游客发言不需要密码.
内 容:
验证码: 验证码
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.
字数限制 1000 字 | UBB代码 开启 | [img]标签 关闭