一 if语句
1.If语句思路分析:
If语句就是当遇到自定义的简单标签时,如果不满足某种条件(属性),就不会执行此标签一下的程序,比如:
If语句可以判断是否登入的用户,如果没有登入,则不会向下执行。
2.代码和注释
(1)if语句的核心---标签处理器 IfTag.java
public class IfTag extends SimpleTagSupport {
private boolean test;
public void setTest(boolean test) {
this.test = test;
}
// 条件判断语句
public void doTag() throws JspException, IOException {
if (test) {
JspFragment jf = this.getJspBody();
jf.invoke(null);
}else{
throw new SkipPageException();
}
}
}
(2)在tld文件中部署
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>c</short-name>
<uri>http://www.csdn.com.cn</uri>
<tag>
<name>if</name>
<tag-class>com.hbsi.web.tag.project.IfTag</tag-class>
<body-content>scriptless</body-content>
<attribute>
<name>test</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
(3)在jsp中的使用
<c:if test="${user!=null}">
好好学习,天天向上,你看到我了吗?
</c:if>
二 If—else分支语句
1.思路分析:
两个分支, 两种情况,正确和错误,当遇到正确的时候执行什么,当遇到错误的时候执行什么,而传过来的是对的还是错的必须要通过一个共同的变量来显示的,所以还要有一个标签用来存储共同的变量,总的来说要用三个标签,一个是存储正确的,一个是错误的,一个是存储公共的boolean变量
2.标签的架构
<c:choose> -------ChooseTag.java
<c:when test=””></c:when> WhenTag.java
<c:otherwise></c:otherwise> OtherwiseTag.java
</c:choose>
3.代码和注释
(1)首先创建一个ChooseTag.java---用来显示父类的标签
public class ChooseTag extends SimpleTagSupport {
private boolean flag=false;
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
public void doTag() throws JspException, IOException {
JspFragment jf = this.getJspBody();
jf.invoke(null);
}
(2)创建第一个子类 WhenTag.java
public class WhenTag extends SimpleTagSupport {
private boolean test;
public void setTest(boolean test) {
this.test = test;
}
public void doTag() throws JspException, IOException {
//获取父标签对象
ChooseTag parent = (ChooseTag) this.getParent();
if(test && !parent.isFlag()){
//处理该标签体
this.getJspBody().invoke(null);
parent.setFlag(true);
}
}
(3)创建第二个子类 Otherwise.java
public class OtherwiseTag extends SimpleTagSupport {
public void doTag() throws JspException, IOException {
ChooseTag parent = (ChooseTag) this.getParent();
if(!parent.isFlag()){
this.getJspBody().invoke(null);
parent.setFlag(true);
}
}
(4)在tld文件中部署
<tag>
<name>choose</name>
<tag-class>com.hbsi.web.tag.project.ChooseTag</tag-class>
<body-content>scriptless</body-content>
</tag>
<tag>
<name>when</name>
<tag-class>com.hbsi.web.tag.project.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.web.tag.project.OtherwiseTag</tag-class>
<body-content>scriptless</body-content>
</tag>
(5)在jsp中使用
<c:choose>
<c:when test="${fg!=null}">注册了,登入中。。。</c:when>
<c:otherwise>没有注册</c:otherwise>
</c:choose>