自定義標籤(二)

 

    

1、演示簡單標籤的使用

  1. 使用自定義標籤控制頁面內容(標籤體)是否輸出

public void doTag() throws JspException, IOException {

//JspFragment jf = this.getJspBody();

//jf.invoke(null);

//等價於jf.invoke(this.getJspContext().getOut());

}



  1. 簡單標籤控制標籤後的jsp內容是否執行

public void doTag() throws JspException, IOException {

JspFragment jf = this.getJspBody();

jf.invoke(null);

throw new SkipPageException();

}


  1. 自定義標籤實現內容(標籤體)循環輸出

public void doTag() throws JspException, IOException {

JspFragment jf = this.getJspBody();

for(int i=0; i<5; i++){

jf.invoke(null);

}

}


  1. 自定義標籤修改內容(標籤體)——大小寫轉換

public void doTag() throws JspException, IOException {

JspFragment jf = this.getJspBody();

//爲了獲取JspFragment中的內容,將其輸入一個帶緩衝的Writer中,//在獲取字符串

StringWriter sw = new StringWriter();

jf.invoke(sw);

String content = sw.toString().toUpperCase();

JspWriter out = this.getJspContext().getOut();

out.write(content);

}



2、帶屬性的自定義標籤

1)控制標籤體循環輸出指定次數

在標籤處理類中添加屬性變量及其setter方法

private int times;

public void doTag() throws JspException, IOException {

JspFragment jf = this.getJspBody();

for(int i=0; i<times; i++){

jf.invoke(null);

}

}

public void setTimes(int times) {

this.times = times;

}

tld文件中增加屬性描述<attribute></attribute>

<attribute>

<name>times</name>

<required>true</required>

<rtexprvalue>true</rtexprvalue>

</attribute>


演示<trexprvalue>true</rtexprvalue>

<class3g:mySimpleTag5 times="<%=3+1 %>">

aaaaaaaaa<br>

</class3g:mySimpleTag5>


2)解釋傳參時類型轉換問題,並以Data數據的傳遞演示非基本數據類型的參數傳遞

  • 在標籤處理類中添加Data類型成員及其setter方法

    private Date date;

    public void setDate(Date date) {

    this.date = date;

    }

  • tld中添加屬性描述

    <attribute>

    <name>date</name>

    <required>true</required>

    <rtexprvalue>true</rtexprvalue>

    <type>java.util.Date</type>

    </attribute>

  • jsp中調用

<class3g:mySimpleTag5 times="3" date="<%=new Date() %>">

xxxxxxxx

</class3g:mySimpleTag5>


發佈了59 篇原創文章 · 獲贊 4 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章