<c:choose> <c:when test="..."> ...... </c:when><c:otherwise> ...... </c:otherwise> </c:choose>开发一个我们自己的if...else标签,以此来了解sun自定义标签的内涵。
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@taglib uri="/example" prefix="z" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Hello</title> </head> <body> <z:choose> <z:when test="${user!=null}"> 欢迎您!(*^__^*) </z:when><z:otherwise> 您没有登录!~~(>_<)~~ </z:otherwise> </z:choose> </body> </html>
package org.zyg.web.exampleTag; import java.io.IOException; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.SimpleTagSupport; public class ChooseTag extends SimpleTagSupport { private boolean isDo; public boolean isDo() { //get方法 return isDo; } public void setDo(boolean isDo) { //set方法 this.isDo = isDo; } //控制标签体执行 @Override public void doTag() throws JspException, IOException { this.getJspBody().invoke(null); } }
package org.zyg.web.exampleTag; import java.io.IOException; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.SimpleTagSupport; public class WhenTag extends SimpleTagSupport { private boolean test; public void setTest(boolean test) { this.test = test; } @Override public void doTag() throws JspException, IOException { //得到父标签 ChooseTag parent=(ChooseTag) this.getParent(); if(test && !parent.isDo()){//当test的值为真 this.getJspBody().invoke(null); //因为父类的isDo变量默认值是false,修改isDo是为了给otherwise作参考 parent.setDo(true); } } }
package org.zyg.web.exampleTag; import java.io.IOException; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.SimpleTagSupport; public class OtherWiseTag extends SimpleTagSupport { @Override public void doTag() throws JspException, IOException { ChooseTag parent=(ChooseTag)this.getParent(); if(!parent.isDo()){//当when中的test为假的时候 this.getJspBody().invoke(null); parent.setDo(true); } } }
<tag> <name>choose</name><!-- 标签名 --> <tag-class>org.zyg.web.exampleTag.ChooseTag</tag-class> <body-content>scriptless</body-content><!-- 有无标签体(单标签还是成对标签) --> </tag> <tag> <name>when</name><!-- 标签名 --> <tag-class>org.zyg.web.exampleTag.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>org.zyg.web.exampleTag.OtherWiseTag</tag-class> <body-content>scriptless</body-content><!-- 有无标签体(单标签还是成对标签) --> </tag>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@taglib uri="/example" prefix="z" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Hello</title> </head> <body> <% session.setAttribute("user","zyg"); %> <z:choose> <z:when test="${user!=null}"> 欢迎您!(*^__^*) </z:when><z:otherwise> 您没有登录!~~(>_<)~~ </z:otherwise> </z:choose> </body> </html>
以上就是类似if...else标签的开发。
转载请注明出处:http://blog.csdn.net/acmman/article/details/51187408