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>