继承TagSupport是一个简单且实用也最常用的。
一、需求分析
应用中常用数据字典来管理常用数据。后台数据往往在处理数据实只认字典项的code.显然在页面上需要对其进行转换。以让用户能够认识。所以往往要对这个字典项的code进行翻译。所以可以用标签来实现。
二、标签处理类
public class DictNameTag extends TagSupport { private AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); private DictManager dictManager = (DictManager)ctx.getBean("dictManager"); private String code; public String getCode() { return code; } public void setCode(String code) { this.code = code; } @Override public int doStartTag() throws JspException { String dictName = ""; JspWriter out = this.pageContext.getOut(); if(code!=null && !"".equals(code)){ SystemDict dict = dictManager.getByCode(code,null); if(dict!=null){ if(dict.getCodecontent()!=null) dictName = dict.getCodecontent(); } } try { out.println(dictName); } catch (IOException e) { e.printStackTrace(); } return SKIP_BODY; } @Override public int doEndTag() throws JspException { // TODO Auto-generated method stub return super.doEndTag(); }}
三、tld注册
<tag> <name>dictName</name> <tag-class>com.harmony.dwyj.common.tag.DictNameTag</tag-class> <body-content>empty</body-content> <attribute> <name>code</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag>
四、页面应用:
<h:dictName code="${bean.eventCode}"/>