JSP 2.x 自定義標簽
JSP 1.x的標簽,雖然使用起來非常靈活,但是比較復雜,JSP 2.x提供了一組簡化的標簽寫法
SimpleTagSupport是SimpleTag接口的子類,同時支持參數和標簽體,最核心的方法時doTage
public AddTag extends SimpleTagSupport{
private int num1;
private int num2;
public void doTag() throws JspException,IOException{
this.getJspContext.getOut().write("兩數相加等于:"+(num1+num2));
}
//省略setter、getter方法
}
同樣是實現了計算兩數之和的功能,配置與JSP1.x 一樣
JSP 1.x的標簽體是通過setBodyContent注入到BodyTag,通過getBodyContent取出來的。而SimpleTag是通過一種叫jspFragment的對象實例實現的
//此標簽用于將字符轉換成大寫
public void doTag() throws JspException,IOException{
StringWriter writer = newStringWriter();
JspFragment jspFragment = this.getJspBody();
//通過invoke輸出到指定的writer中,如果參數為空,則輸出到默認的writer, //即getJspContext().getOut()
jspFragment.invoke(writer);
String content =writer.getBuffer().toString();
this.getJspContext().getOut().print(content.toUpperCase());
}
配置如下
<tag>
<name>tagname</name>
<tagclass>com.chen.tags.TagTest</tagclass>
<bodycontent>tagdependent</bodycontent >
<info>tag information</info>
</tag>
這里的<bodycontent>只能是tagdependent,而不能是JSP或者bodycontent
與JSP 1.x不同的是,JSP 2.x標簽可以有多個標簽體,并且可以按照不同順序,不同的次數分別調用標簽體,多個標簽體需要借助JSP的<jsp:attribute>,而且在tld配置的時候,必須配合為fragment類型
<attribute>
<name>body1</name>
<required>false</ required>
<fragment>true</fragment >
</attribute>
本文由用戶 n672 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!