- 需求描述
实现一个类似于如下图的自定义标签 - 三个标签处理器类
-myChoose
-myWhen
-myOther
在父类Mychoose中定义一个是否执行的标志位opreated。
myWhen中有一个判断条件是否成立的标志satisfied。
(1)如果satisfied=true且opreated=false,则执行myWhen,执行完之后将opreated置为true
(2)如果如果satisfied=false,则不执行当前的myWhen
(3)如果如果opreated=false,则执行myOther
MyChoose 标签处理器类
public class MyChoose extends SimpleTagSupport {
public boolean isOperated=false;
public boolean isOperated() {
return isOperated;
}
public void setOperated(boolean operated) {
isOperated = operated;
}
@Override
public void doTag() throws JspException, IOException {
System.out.println("this is myChoose doTag...");
getJspBody().invoke(null);
}
}
myWhen标签处理器类
public class MyWhen extends SimpleTagSupport {
private boolean satisfied=true;
public boolean isSatisfied() {
return satisfied;
}
public void setSatisfied(boolean satisfied) {
this.satisfied = satisfied;
}
@Override
public void doTag() throws JspException, IOException {
System.out.println("条件是否满足:"+ satisfied);
if (satisfied) {
MyChoose myChoose = (MyChoose) getParent();
boolean operated = myChoose.isOperated();
if (!operated) {
getJspBody().invoke(null);
myChoose.setOperated(true);
}
}
}
}
myOther标签处理器类
public class MyOther extends SimpleTagSupport {
@Override
public void doTag() throws JspException, IOException {
MyChoose myChoose=(MyChoose) getParent();
boolean operated = myChoose.isOperated();
if(operated==false ){
getJspBody().invoke(null);
}
}
}
- 文件描述符
在这里注意第一个坑:myWhen的属性中,rtexprvalue值一定要置为true,表示其可以接受el表达式,否则会报According to TLD or attribute directive in tag file, attribute [satisfied] does not accept any expressions 错误
<tag>
<name>myChoose</name>
<tag-class>com.paul.tag.MyChoose</tag-class>
<body-content>scriptless</body-content>
</tag>
<tag>
<name>myWhen</name>
<tag-class>com.paul.tag.MyWhen</tag-class>
<body-content>scriptless</body-content>
<attribute>
<name>test</name>
<required>true</required>
<!--一定要置为true-->
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
<tag>
<name>myOther</name>
<tag-class>com.paul.tag.MyOther</tag-class>
<body-content>scriptless</body-content>
</tag>
- 使用
这里包含第二个坑:页面中使用el表达式
<%@ page isELIgnored=“false”%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false"%>
<%@ taglib prefix="puhao" uri="puhao" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<puhao:myChoose>
<puhao:myWhen satisfied="${param.score > 90}">优秀</puhao:myWhen>
<puhao:myWhen satisfied="${param.score > 60}">及格</puhao:myWhen>
<puhao:myOther>不及格</puhao:myOther>
</puhao:myChoose>
</body>
</html>
http://localhost:8080/tag/myChoose.jsp?score=100