天天看點

自定義标簽的屬性

自定義标簽的屬性

今天我們主要來說一下自定義标簽的屬性,前幾次我們做得都沒有用到标簽的屬性,那什麼是标簽的屬性呢,同樣我們通過幾個執行個體來介紹一下自定義标簽的屬性。

通過屬性循環輸出與輸出目前時間

   private int times; 

   private Date date;

   public void setDate(Date date) {

     this.date = date;

   }

   public void setTimes(inttimes) {

     this.times = times;

   }

   public void doTag() throwsJspException, IOException {

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

        this.getJspBody().invoke(null);

     }

     this.getJspContext().getOut().write(date.toString());

   }

JSP/

<class3g:LoopOutTag date="<%=new Date() %>" times="5">

     測試<br/>

</class3g:LoopOutTag>

Time是循環的次數,date是目前的日期

自定義标簽代替If語句

   private boolean expr;

   public void setExpr(booleanexpr) {

     this.expr = expr;

   }

   @Override

   public void doTag() throwsJspException, IOException {

     if(expr){

        this.getJspBody().invoke(null);

     }

   }

/JSP/

   <class3g:ifTagexpr="${user==null }">

     <h1>aaaaaaaaaaaaaaaaa</h1>

   </class3g:ifTag>

Expr屬性通過判斷語句的正否,決定标簽體的輸出與否,相當于if

If else語句

l 編寫choose标簽,無屬性,但有一個成員invoked,要為其編寫setter和getter方法,注意doTag中需要輸出标簽體

   privateboolean invoked;//false:沒有子标簽被執行 true:某子标簽被執行

   publicboolean isInvoked() {

     returninvoked;

   }

   publicvoid setInvoked(boolean invoked) {

     this.invoked= invoked;

   }

   @Override

   publicvoid doTag() throws JspException,IOException {

     this.getJspBody().invoke(null);

   }

l 編寫子标簽when标簽,有boolean屬性exp,

   privateboolean expr;

   publicvoid setExpr(boolean expr) {

     this.expr= expr;

   }

   @Override

   publicvoid doTag() throws JspException, IOException {

     ChooseTag ct = (ChooseTag) this.getParent(); 

     if(ct.isInvoked()!=true && expr){

        this.getJspBody().invoke(null);

        ct.setInvoked(true);

     }

   }

l  編寫子标簽otherwise标簽,無屬性,無成員變量

   @Override

   public void doTag() throwsJspException, IOException {

     ChooseTagct = (ChooseTag) this.getParent();

     if(ct.isInvoked()==false){

        this.getJspBody().invoke(null);

        ct.setInvoked(true);

     }

   }