1.首先创建实现了tag功能的辅助类,功能是改变主体文本的颜色。这个类可以继承tagsupport或者bodytagsupport,两者的差别是前者适用于没有主体的标签,而后者适用于有主体的标签。如果选择继承tagsupport,可以实现dostarttag和doendtag两个方法实现tag的功能,如果选择继承bodytagsupport,可以实现doafterbody这个方法。核心代码如下所示:
import java.io.ioexception;
import javax.servlet.jsp.jspwriter;
import javax.servlet.jsp.tagext.*;
/** *//**
*
* @author administrator
*/
public class messagewritertaghandler extends bodytagsupport...{
//主体的字体颜色属性
protected string _fontcolor = "black";
/** *//** creates a new instance of messagewritertaghandler */
public messagewritertaghandler() ...{
}
public string getfontcolor() ...{
return _fontcolor;
}
public void setfontcolor(string fontcolor) ...{
_fontcolor = fontcolor;
}
public int doafterbody()...{
bodycontent bc = this.getbodycontent();
jspwriter out = bc.getenclosingwriter();
stringbuffer sb = new stringbuffer();
try ...{
sb.append("<font color="");
sb.append(_fontcolor);
sb.append("">");
sb.append(bc.getstring());
sb.append("</font>");
out.print(sb.tostring());
} catch (ioexception ex) ...{
//ex.printstacktrace();
}
return eval_page;
}
}
2.编写.tld文件,该文件是tag的描述,需要说明的是tag的attribute的required要设置为true,否则的话标签的功能有可能无法使用。具体原因我还不清楚。tld的代码如下所示:
<?xml version="1.0" encoding="utf-8"?>
<taglib version="2.0" 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 web-jsptaglibrary_2_0.xsd">
<tlib-version>1.0</tlib-version>
<short-name>writer</short-name>
<uri>tags/messagewriter</uri>
<tag>
<name>write</name>
<tag-class>com.lilijun.tags.messagewritertaghandler</tag-class>
<body-content>jsp</body-content>
<attribute>
<name>fontcolor</name>
<required>true</required>>
</attribute>
</tag>
</taglib>
新闻热点
疑难解答