public static void main(String[] args) throws Exception {
//资源文件为Message_CN.propetties一般会专门将一个包用来存放本例中com.resource是专门用来存放资源文件的包。
//资源绑定工具,专门为properties属性配置文件准备工具类
//该配置文件需要是属性配置文件,并且该配置文件放在类路径当中,以类名方式对待。
ResourceBundle bundle = ResourceBundle.getBundle(“com.resource.Message_CN”);
String s = bundle.getString(“0”);
System.out.println(s);
}
以上就是资源绑定的简单实现步骤,但是程序开发中不可能这样来回写一段重复的代码,所以下面我把它简单的做成一个工具类,以便于以后更好的使用。
先写一个字符串工具类放在你项目中的工具包中:
/**
- 字符串工具类
- @author haoyu
/
public class StringUtil {
/*- 工具类的构造函数一般都是私有化的
/
private StringUtil(){
}
/*- 类加载的时候绑定资源
/
private static ResourceBundle bundle = ResourceBundle.getBundle(“com.resource.Message_CN”);
/*
- 类加载的时候绑定资源
- 通过配置文件中的key获取 value
*/
public static String getTextBycode(String code){
return bundle.getString(code);
}
}
接下来直接使用这个工具类中定义的方法读取资源文件中的value值。
使用jsp页面输出示例为:
<%=StringUtil.getTextBycode(user.getOrgtype()) %>
本例中的user.getOretype返回的是一个字符串,不用在意
- 工具类的构造函数一般都是私有化的