在做这个项目的过程中有很多地方数据都是用到数据字典的。
每次在jsp页面显示时还得在service转换,因此写这个自定义标签来处理这个问题。
实质上就是创建一个将code转text的方法,用一个标签来自己调用一下。
1、创建方法
private String code; //getter setter
public int doStartTag() throws JspTagException {
try {
if (null == code) {
pageContext.getOut().write("");
} else {
String name = dictItemService.getItemName(code);
if (name != null) {
pageContext.getOut().write(name);
} else {
pageContext.getOut().write(code);
}
}
} catch (Exception ex) {
logger.error(ErrorUtil.getErrMsg(ex));
return SKIP_PAGE;
}
return EVAL_BODY_INCLUDE;
}
这里的 dictItemService 一般注入或者注解注入 为null的话,最好用context获取一下子。
ServletContext application = ServletActionContext.getRequest().getSession().getServletContext();
ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(application);
DictItemService dictItemService = (DictItemService)context.getBean("dictItemService");
2、设置自定义标签
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN"
"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>reg Tag Library</shortname>
<uri>http://www.reg.com</uri>
<info></info>
<tag>
<name>codeConvert</name>
<tagclass>cn.com.cherish.utils.CodeConvertTag</tagclass>
<bodycontent>empty</bodycontent>
<info>将数据字典代码转换为显示文本</info>
<attribute>
<name>code</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
3、方法和标签都定义好之后
在页面上引入就可以用了。
<%@ taglib uri="http://www.reg.com" prefix="reg" %>
结果:
<reg:codeConvert code="${requestScope.user.sex}"/> man : 男