else … if …
<c:if test=””>aaa</c:if>——IfTag.java
<c:else>bbbb</c:else>——ElseTag.java
放在父标签中
让if和else的两个对象处理器共享一个boolean对象,来通知各自的标签处理器是否执行下面代码
<c:choose>——ChooseTag.java
<c:whentest=”${user != null}”>——WhenTag.java
This is my page
</c:when>
<c:other>——OtherTag.java
If user is not ex
</c:other>
</c:choose>
代码:
ChooseTag.java部分
private boolean flag=false;
//因为要在子类中读取flag的值,所有需要get方法
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
@Override
public void doTag() throws JspException, IOException {
// TODO Auto-generatedmethod stub
JspFragment jf=this.getJspBody();
jf.invoke(null);
}
Otherwise.java部分:
public void doTag() throws JspException, IOException {
// TODO Auto-generatedmethod stub
//获取父标签体对象
ChooseTag parent=(ChooseTag)this.getParent();
if(!parent.isFlag()){
this.getJspBody().invoke(null);
parent.setFlag(true);
}
}
WhenTag.java
private boolean test;
public void setTest(boolean test) {
this.test = test;
}
@Override
public void doTag() throws JspException, IOException {
// TODO Auto-generatedmethod stub
//父标签对象
ChooseTag parent=(ChooseTag)this.getParent();
if(test && !parent.isFlag()){//test是真,并且没有分支被执行过
//处理标签体
this.getJspBody().invoke(null);
parent.setFlag(true);
}
}
TestIf.jsp部分
<%session.setAttribute("user","zhangsan") ;%>
<br/>__________________________________<br/>
<!-- 测试if、else标签 -->
<c:choose>
<c:when test="${user !=null}">aaaaa</c:when>
<c:otherwise>bbbbbb</c:otherwise>
</c:choose>
c.tld部分
<?xml version="1.0"encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC "-//SunMicrosystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>c</short-name>
<uri>http://www.c.com</uri>
<tag>
<name>if</name>
<tag-class>com.hbsi.tag.IfTag</tag-class>
<body-content>scriptless</body-content>
<attribute>
<name>test</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
<tag>
<name>choose</name>
<tag-class>com.hbsi.tag.ChooseTag</tag-class>
<body-content>scriptless</body-content>
</tag>
<tag>
<name>when</name>
<tag-class>com.hbsi.tag.WhenTag</tag-class>
<body-content>scriptless</body-content>
<attribute>
<name>test</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
<tag>
<name>otherwise</name>
<tag-class>com.hbsi.tag.OtherwiseTag</tag-class>
<body-content>scriptless</body-content>
</tag>
</taglib>