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>