考虑一下片段 的 loop.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="mypredefinedtaglibrary" prefix="my" %>
<html>
<head>
</head>
<body>
<my:looping end="5" start="1">
<p>My Name is Khan</p><br/>
</my:looping>
</body>
</html>
MyTagHandlerForLoop.java
public class MyTagHandlerForLoop extends TagSupport {
private static final long serialVersionUID = 1L;
private int start = 0;
private int end = 0;
public void setStart(int start) {
this.start = start;
}
public void setEnd(int end) {
this.end = end;
}
@Override
public int doAfterBody() throws JspException {
if (start < end) {
start++;
return EVAL_BODY_AGAIN;
} else {
return SKIP_BODY;
}
}
@Override
public int doStartTag() throws JspException {
return EVAL_BODY_INCLUDE;
}
}
mytags.tld
<tag>
<name>looping</name>
<tag-class>org.customtags.MyTagHandlerForLoop</tag-class>
<body-content>scriptless</body-content>
<attribute>
<name>start</name>
<required>true</required>
</attribute>
<attribute>
<name>end</name>
<required>true</required>
</attribute>
</tag>
web.xml中的配置
<jsp-config>
<taglib>
<taglib-uri>mypredefinedtaglibrary</taglib-uri>
<taglib-location>/WEB-INF/tags/mytags.tld</taglib-location>
</taglib>
</jsp-config>
O / P反映为:
My Name is Khan
My Name is Khan
My Name is Khan
My Name is Khan
My Name is Khan
当我在调试模式下运行时,首先会创建一个对象, 那么设定者是c / d,结果是
start = 1
end = 5
if (start < end) {
start++;
return EVAL_BODY_AGAIN;
此循环过程执行4次。
那么,为什么 我的名字是汗 输出5次。不应该是4次。
答案 0 :(得分:1)
“评估身体”,输出“我的名字是汗”,运行5次。首先从doStartTag()方法开始,然后,如你所说,doAfterBody()方法的4倍。
此图表阐明了经典自定义标签的工作原理。