因为有3个标签,所以写3个标签处理器类
1.ChooseTag
public class ChooseTag extends SimpleTagSupport { public Boolean tag = true; public Boolean getTag() { return tag; } public void setTag(Boolean tag) { this.tag = tag; } @Override public void doTag() throws JspException, IOException { JspFragment jspBody = this.getJspBody(); jspBody.invoke(null); super.doTag(); } }
2.WhenTag
public class WhenTag extends SimpleTagSupport { public Boolean test; public Boolean getTest() { return test; } public void setTest(Boolean test) { this.test = test; } @Override public void doTag() throws JspException, IOException { ChooseTag chooseTag = (ChooseTag) this.getParent(); Boolean tag = chooseTag.getTag(); if (tag && this.getTest()) { chooseTag.setTag(false); JspFragment jspBody = this.getJspBody(); jspBody.invoke(null); } super.doTag(); } }
3.OtherwiseTag
public class OtherwiseTag extends SimpleTagSupport{ @Override public void doTag() throws JspException, IOException { ChooseTag chooseTag = (ChooseTag) this.getParent(); Boolean tag = chooseTag.getTag(); if(tag){ JspFragment jspBody = this.getJspBody(); jspBody.invoke(null); } super.doTag(); } }
写tld文件
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd"> <taglib> <tlibversion>1.2</tlibversion> <jspversion>1.1</jspversion> <shortname>mylib</shortname> <uri>http://www.fz.song.myLib</uri> <tag> <name>choose</name> <tagclass>fz.song.tag.ifelse.ChooseTag</tagclass> <bodycontent>scriptless</bodycontent> </tag> <tag> <name>when</name> <tagclass>fz.song.tag.ifelse.WhenTag</tagclass> <bodycontent>scriptless</bodycontent> <attribute> <name>test</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag> <tag> <name>otherwise</name> <tagclass>fz.song.tag.ifelse.OtherwiseTag</tagclass> <bodycontent>scriptless</bodycontent> </tag> <tag> <name>foreach</name> <tagclass>fz.song.tag.foreach.ForeachTag</tagclass> <bodycontent>scriptless</bodycontent> <attribute> <name>items</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> <attribute> <name>var</name> <required>true</required> <rtexprvalue>false</rtexprvalue> </attribute> </tag> </taglib>
jsp页面
<%@ taglib uri="http://www.fz.song.myLib" prefix="x"%> <x:choose> <x:when test="${10>1}">true</x:when> <x:otherwise>false</x:otherwise> </x:choose>
原文:http://www.cnblogs.com/songfahzun/p/4918925.html