*博主也做过几个或大或小的web后台项目,其中数据库必不可少有字典表用来存储一些常用的业务字典,页面渲染也少不了各种标签以及表达式.我们在查询数据时候,主表一般会存储字典表的主键,然后通过联表查询来获取对应的字典.现在我想分享一种"另一种方式",和大家一起讨论学习*
思路如下:
1.在web容器初始化时,将字典表中数据全部缓存起来(HashMap,或者第三方缓存).
2.数据查询时不再与字典表进行关联.
3.页面渲染时候用自定义tld标签进行数据展示.
大家也许会对tld标签陌生,但是提及JSTL表达式的fn函数大家一定不陌生,fn函数给我们提供的方法在这里我不再进行一一阐述.其中的实现也是通过java来进行实现(是不是很熟悉???)
自定义tld只不过是对其进行自定义扩展,废话少说,回归正题,开始coding
//通过类型获取字典列表
public static List<EtlDict> getEtlDictList(String type){
//创建全局缓存
Map<String, List<EtlDict>> etlDictMap = (Map<String, List<EtlDict>>)CacheUtils.get(CACHE_ETLDICT_MAP);
if (etlDictMap==null){
etlDictMap = Maps.newHashMap();
//字典表按照类型进行存储
for (EtlDict gt : etlDictDao.findAllList(new EtlDict())){
List<EtlDict> dictList = etlDictMap.get(gt.getType());
if (dictList != null){
dictList.add(gt);
}else{
etlDictMap.put(gt.getType(), Lists.newArrayList(gt));
}
}
CacheUtils.put(CACHE_ETLDICT_MAP, etlDictMap);
}
List<EtlDict> etlDictList = etlDictMap.get(type);
if (etlDictList == null){
etlDictList = Lists.newArrayList();
}
return etlDictList;
}
//通过类型和值获取标签
public static String getEtlDictLabel(String value, String type, String defaultValue){
if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(value)){
for (EtlDict gt : getEtlDictList(type)){
if (type.equals(gt.getType()) && value.equals(gt.getValue())){
return gt.getLabel();
}
}
}
return defaultValue;
}
进行自定义tld文件创建与定义
<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
version="2.0">
<description>JSTL 1.1 functions library</description>
<display-name>JSTL functions etl</display-name>
<tlib-version>1.1</tlib-version>
<short-name>fna</short-name>
<uri>http://java.sun.com/jsp/jstl/functionse</uri>
<function>
<description>方法描述</description>
<name>方法名字</name>
<function-class>方法所在类</function-class>
<function-signature>返回值 方法名(参数)</function-signature>
<example>运用举例</example>
</function>
<function>
<description>获取字典对象列表</description>
<name>getEtlDictList</name>
<function-class>gt.com.etl.common.utils.EtlDictUtils</function-class>
<function-signature>java.util.List getEtlDictList(java.lang.String)</function-signature>
<example>${fna:getEtlDictList(type)}</example>
</function>
<function>
<description>通过类型和值获取标签</description>
<name>getEtlDictLabel</name>
<function-class>gt.com.etl.common.utils.EtlDictUtils</function-class>
<function-signature>java.lang.String getEtlDictLabel(java.lang.String, java.lang.String, java.lang.String)</function-signature>
<example>${fna:getEtlDictLabel(value, type, defaultValue)}</example>
</function>
自定义的tld文件引用方法和jstl的标签引用大同小异
在页面用使用自定义的tld标签
<td>
${fna:keepTwoDecimal(asset.costPrice)}
</td>
<td>
${fna:keepTwoDecimal(asset.sellPrice)}
</td>
<td>
${fna:getEtlDictLabel(asset.source,'source','')}
</td>
编码完毕,您看懂了么??
和大家分享目的有两点:
1.可以通过自定义标签随心所欲处理jstl自身提供标签所无法完成的逻辑 2.字典的另一种实现使用方式,撇开性能不谈.
欢迎大家指点交流…….