java web日常开发中,jsp页面经常会取数据字典的值,比如订单状态:审核中、已通过、不通过;学历:初中、高中、大学、研究生等等。通常情况下我们是将这种常量数据配置成数据字典,取得时候直接通过自定义标签来获取。首先我们会创建一个tld文件,放在项目的WEB-INFO文件夹下面,主要声明处理类和处理方法以及自定的标签名称。类似下面的这个文件:
JSTL 1.1 functions library
JSTL functions sys
1.1
fns
/fns-tags
获取字典表值
getDictLabel
com.test.DictUtil
java.lang.String getDictLabel(java.lang.String ,java.lang.String)
${fns:getDictLabel(type,code)}
获取字典表值列表
getDictList
com.test.DictUtil
java.util.List getDictList(java.lang.String)
${fns:getDictList(type)}
上面的tld文件主要定义了两个标签,使用方法分别为:
获取数据字典的值 ${fns:getDictLabel(type,code)},
获取数据字典列表 ${fns:getDictList(type)}
这两个标签对应的标签类为com.test.DictUtil,主要有两个方法,如下:
packagecom.test;importjava.math.BigDecimal;importjava.util.ArrayList;importjava.util.List;importjavax.annotation.PostConstruct;importorg.apache.commons.lang3.StringUtils;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Component;importcom.test.entity.dict.DictBase;importcom.yifen.util.StringUtil;importcom.test.service.dict.DictService;/*** 自定义标签取值*/@Componentpublic classDictUtil {
@Autowired(required= false)private DictServicedictService;private staticDictUtil dictUtil;
@PostConstructpublic voidinit() {
dictUtil= this;
dictUtil.dictService= this.dictService;
}/*** 根据类型type和编码code获取唯一的字典值
*
*@paramtype
*@paramcode
*@return
*/
public staticString getDictLabel(String type, String code) {
String result= "-";
DictBase tempDict= null;
DictBase dictBase= newDictBase();
dictBase.setDictType(type);
dictBase.setDictValue(code);if (!"".equals(code) && !"".equals(type)) {
tempDict=dictBaseUtil.dictService.getDictLabel(dictBase);
}if (tempDict != null) {
result=tempDict.getDictName();
}returnresult;
}/*** 根据类型type获取字典列表
*
*@paramtype
*@paramcode
*@return
*/
public static ListgetDictList(String type) {
List result = null;if (!StringUtil.isEmpty(type)) {
result=dictBaseUtil.dictService.getDictList(type);
}if (result == null) {
result= new ArrayList();
}returnresult;
}}
然后在jsp文件的中应用一下tld文件就可以直接使用该标签获取数据字典的值了,下面例子为页面获取一个订单状态下拉框,该订单状态就是配置到数据字典的
/**引用tld文件**/
/**使用方式**/
订单状态:
请选择
selected="selected">${item.dictName }