数据字典在项目中经常会用的内容,比如用于动态生成下拉选择项,多选项,或者单选项,主要包括的内容有字典名称+字典项。在本文中介绍两种方法。
一、数据库
使用数据库将字典存放在表中,在添加或者修改的时候需要刷新数据字典的内容。其ddl如下:
CREATE TABLE `sys_dict` (
`dname` varchar(128) NOT NULL DEFAULT '' COMMENT '字典名',
`dcode` varchar(128) NOT NULL DEFAULT '' COMMENT '字典键',
`dvalue` varchar(128) DEFAULT NULL COMMENT '值',
`dmemo` varchar(256) DEFAULT NULL COMMENT '备注',
PRIMARY KEY (`dname`,`dcode`)
) ENGI
二、配置文件的方式
将配置文件写入到xml或者properties文件中,通过程序解析后存储到map中。在此文中选用json数据的方式。
其数据结构如下
public static Map<String, List<DictItem>> dict = new HashMap<String, List<DictItem>>();
初始化赋值
public static void init(File f) {
try {
//读取文件
InputStream is = new FileInputStream(f);
Properties pros = new Properties();
pros.load(is);
//解析properties文件
Iterator<Object> itor = pros.keySet().iterator();
while (itor.hasNext()) {
String key = (String) itor.next();
String value = pros.getProperty(key);
dict.put(key, process(value));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
取值
/**
* 查询所有的字典数据
*
* @author _13[526028311@qq.com]
* @param name 字典名称
* @return
* @since JDK 1.7
*/
public static List<DictItem> getDicts(String name) {
return dict.get(name);
}
/**
* 查询某个字典下某个code对应的数据
*
* @author _13[526028311@qq.com]
* @param name 字典名称
* @param code 字典下某种code
* @return
* @since JDK 1.7
*/
public static DictItem getDictItem(String name, String code) {
List<DictItem> ls = dict.get(name);
DictItem item = null;
for (DictItem i : ls) {
if (code.equals(i.getCode())) {
item = i;
}
}
return item;
}
通过自定义标签可以使得数据字典的使用更加灵活