<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>