jsp自定義標簽之ifelse與遍歷自定義標簽示例

字號:


    這篇文章主要介紹了jsp自定義標簽之ifelse與遍歷自定義標簽,需要的朋友可以參考下
    第一個示例:
    簡單的jsp自定標簽獲取內(nèi)容:
    首先創(chuàng)建一個jsp實例類然后繼承SimpleTagSupport類
    然后實現(xiàn)父類的doTag()方法
    在這個方法里獲取標簽體里的內(nèi)容this.getJspBody();
    返回的是JspFragment 類,根據(jù)這個類對象調(diào)用invoke(this.getJspContext().getOut());
    這個方法里面也可以寫空,所表達的意思也是輸出到瀏覽器;
    代碼如下:
    public class SimpleDmeo1 extends SimpleTagSupport {
    @Override
    public void doTag() throws JspException, IOException {
    JspFragment js =this.getJspBody();
    js.invoke(null);
    }
    }
    然后在寫tld文件標簽庫描述文件,和jsp文件,這些都較為簡單
    如果不想執(zhí)行某個內(nèi)容就拋出異常
    throw new skipPageException();和面內(nèi)容就不會顯示
    接下來是一個帶屬性的jsp自定義標簽文件
    代碼如下:
    public class SimpleDmeo1 extends SimpleTagSupport {
    private int counts;
    public void setCounts(int counts) {
    this.counts = counts;
    }
    @Override
    public void doTag() throws JspException, IOException {
    JspFragment js =this.getJspBody();
    for(int i=0;i<counts;i++){ //循環(huán)獲取
    js.invoke(null);
    }
    }
    }
    <description>A tag library exercising SimpleTag handlers.</description>
    <tlib-version>1.0</tlib-version>
    <short-name>c</short-name>前綴名
    <uri>http://www.csdn.com</uri>
    <tag>
    <name>demo</name>
    <tag-class>com.csdn.simple.SimpleDmeo1</tag-class>
    <body-content>scriptless</body-content>
    <attribute>
    <name>counts</name>
    <required>true</required>
    <rtexprvalue>true</rtexprvalue>
    </attribute>
    </tag>
    然后再jsp文件 中寫出內(nèi)容;
    代碼如下:
    <hbsi:demo counts="3">aaaaaaa<br/></hbsi:demo> //輸出三編
    JspFragment js = this.getJspBody();
    StringWriter jw = new StringWriter();
    js.invoke(jw);
    String s = jw.toString().toUpperCase();
    JspWriter out =this.getJspContext().getOut();
    for(int i=0;i<counts2;i++){
    out.print(s);
    }
    }
    這是轉(zhuǎn)成大寫的代碼,其他的都一致;
    關(guān)于if else的代碼,太多,我放到資源里了,有必要的話可以下載下來,僅供參考。