JSP 2.x 自訂標籤,jsp2.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>