javaWeb 使用jsp开发 if else 标签

1.jsp页面调用代码

<t:choose>
    <t:when test="${user==null }">还没有登录</t:when>
    <t:otherwise>欢迎您: ${user }</t:otherwise>
</t:choose>

2.tld文件代码

    <tag>
        <name>choose</name>
        <tag-class>de.bvb.web.tag.ChooseTag</tag-class>
        <body-content>scriptless</body-content>
    </tag>
    <tag>
        <name>when</name>
        <tag-class>de.bvb.web.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>de.bvb.web.tag.OtherWiseTag</tag-class>
        <body-content>scriptless</body-content>
    </tag>

3.标签实现类代码

3.1 父标签代码

package de.bvb.web.tag;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;

public class ChooseTag extends SimpleTagSupport {
    private boolean executed;

    public boolean isExecuted() {
        return executed;
    }

    public void setExecuted(boolean executed) {
        this.executed = executed;
    }

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

3.2 if 标签代码

package de.bvb.web.tag;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;

public class WhenTag extends SimpleTagSupport {
    private boolean test;

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

    @Override
    public void doTag() throws JspException, IOException {
        ChooseTag parent = (ChooseTag) this.getParent();
        if (!parent.isExecuted() && test) {
            this.getJspBody().invoke(null);
            parent.setExecuted(true);
        }

    }

}

3.3 else 标签代码

package de.bvb.web.tag;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;

public class OtherWiseTag extends SimpleTagSupport {
    @Override
    public void doTag() throws JspException, IOException {
        ChooseTag parent = (ChooseTag) this.getParent();
        if (!parent.isExecuted()) {
            this.getJspBody().invoke(null);
            parent.setExecuted(true);
        }
    }

}
原文地址:https://www.cnblogs.com/Westfalen/p/5978732.html