JSP 2.x 自訂標籤,jsp2.x自訂標籤

來源:互聯網
上載者:User

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>


 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.