您的位置:首页 > Web前端 > JavaScript

jstl c:choose>、<c:when>和<c:otherwise>标签的自定义开发

2016-04-25 19:26 603 查看
<c:choose>
<c:when test="${param.age>24}">大学毕业</c:when>
<c:when test="${param.age>20}">高中毕业</c:when>
<c:otherwise>高中以下学历</c:otherwise>
</c:choose>

》开发三个标签 choose when otherwise

》其中when标签中有一个Boolean类型的属性:test

》choose是when和otherwise的父标签,when在otherwise之前使用

》在父标签中定义一个“全局”的Boolean类型的flag:用于判断子标签在满足条件的情况下是否执行

>若when的test为true,且when的父标签flag也为true,则执行when的标签体(正常输出标签体内容)同时将flag设置为false

>若when的test为true,且when的父标签flag为false,则不执行标签体

>若flag为true,otherwise执行标签体

choose类



public class ChooseTag extends SimpleTagSupport {
private boolean flag = true;
public void setFlag(boolean flag) {
this.flag = flag;
}
public boolean isFlag() {
return flag;
}
@Override
public void doTag() throws JspException, IOException {
getJspBody().invoke(null);
}


when类



public class WhenTag extends SimpleTagSupport {
private boolean 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);
}
}
}


otherwise类



public class OtherWiseTag extends SimpleTagSupport {
@Override
public void doTag() throws JspException, IOException {
ChooseTag chooseTag = (ChooseTag) getParent();
if(chooseTag.isFlag()){
getJspBody().invoke(null);
}
}


test.jsp

<!-- 导入标签库文件(自定义) -->
<%@taglib uri="http://www.wlc.com/myTag/core" prefix="wlc"%>

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


tld文件

<tag>
<name>choose</name>
<tag-class>cn.stud.wlc.tag.ChooseTag</tag-class>
<body-content>scriptless</body-content>
</tag>

<tag>
<name>when</name>
<tag-class>cn.stud.wlc.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>cn.stud.wlc.tag.OtherWiseTag</tag-class>
<body-content>scriptless</body-content>
</tag>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: