自定义标签的属性
今天我们主要来说一下自定义标签的属性,前几次我们做得都没有用到标签的属性,那什么是标签的属性呢,同样我们通过几个实例来介绍一下自定义标签的属性。
通过属性循环输出与输出当前时间
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);
}
}