jsp中使用简单标签实现自定义嵌套标签
开发类似sun公司提供的<c:if> <c:else>标签
实现步骤:
第一步:编写一个父标签处理器Choose.java
public class Choose extends SimpleTagSupport {
//标记执行那个标签
private boolean isDo;
public boolean isDo() {
return isDo;
}
public void setDo(boolean isDo) {
this.isDo = isDo;
}
//父标签控制标签体执行
public void doTag() throws JspException, IOException {
getJspBody().invoke(null);
}
}
第二步:编写一个 子标签WhenTag.java 、OtherwithTag.java 类似 if else
public class WhenTag extends SimpleTagSupport {
private boolean test;
public void setTest(boolean test) {
this.test = test;
}
public void doTag() throws JspException, IOException {
Choose parent=(Choose) getParent();
if(test && !parent.isDo())
{
getJspBody().invoke(null);
parent.setDo(true);
}
}
}
public class OtherwithTag extends SimpleTagSupport {
public void doTag() throws JspException, IOException {
Choose parent=(Choose) this.getParent();
if(!parent.isDo())
{
getJspBody().invoke(null);
parent.setDo(true);
}
}
}
第三步:编写一个*.tld文件描述标签处理器
<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
version="2.0">
<description>A tag library exercising SimpleTag handlers.</description>
<tlib-version>1.0</tlib-version>
<short-name>SimpleTagLibrary</short-name>
<uri>http://www.liyong.nesttag</uri>
<tag>
<description>show client IP</description>
<name>choose</name>
<tag-class>com.liyong.nestTag.Choose</tag-class>
<!-- 标签体不为空 这与传统标签不同 JSP -->
<body-content>scriptless</body-content>
</tag>
<tag>
<description>show client IP</description>
<name>when</name>
<tag-class>com.liyong.nestTag.WhenTag</tag-class>
<body-content>scriptless</body-content>
<attribute>
<name>test</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
<tag>
<description>show client IP</description>
<name>otherwith</name>
<tag-class>com.liyong.nestTag.OtherwithTag</tag-class>
<body-content>scriptless</body-content>