JavaWeb--自定义标签4--带父标签的自定义标签

 父标签:ChooseTag

package tagTest;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.IOException;

public class ChooseTag extends SimpleTagSupport {

    private boolean flag = true;

    public boolean isFlag() {
        return flag;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }

    @Override
    public void doTag() throws JspException, IOException {
        getJspBody().invoke(null);
    }
}

  子标签1:WhenTag

package tagTest;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.IOException;

public class WhenTag extends SimpleTagSupport {

    private boolean test;

    public boolean isTest() {
        return test;
    }

    public void setTest(boolean test) {
        this.test = test;
    }

    @Override
    public void doTag() throws JspException, IOException {

        if(test){
            ChooseTag chooseTag = (ChooseTag) getParent();
            boolean flag = chooseTag.isFlag();
            if(flag){
                getJspBody().invoke(null);
                chooseTag.setFlag(false);
            }
        }
    }
}

  子标签2:OtherwiseTag

package tagTest;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.IOException;

public class OtherwiseTag extends SimpleTagSupport {

    @Override
    public void doTag() throws JspException, IOException {
        ChooseTag chooseTag = (ChooseTag)getParent();
        boolean flag = chooseTag.isFlag();

        if(flag){
            getJspBody().invoke(null);
        }
    }
}

  配置tld文件

 <tag>
        <name>choose</name>
        <tag-class>tagTest.ChooseTag</tag-class>
        <body-content>scriptless</body-content>
    </tag>

    <tag>
        <name>when</name>
        <tag-class>tagTest.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>tagTest.OtherwiseTag</tag-class>
        <body-content>scriptless</body-content>
    </tag>

  编写jsp文件

<sky:testForEach collection="${requestScope.customers}" var="cust">${cust.id} -- ${cust.name}<br></sky:testForEach>

<sky:choose>
    <sky:when test="${param.age > 24}">大学毕业</sky:when>
    <sky:when test="${param.age > 20}">高中毕业</sky:when>
    <sky:otherwise>高中以下</sky:otherwise>
</sky:choose>

  

原文地址:https://www.cnblogs.com/SkyeAngel/p/8056767.html