1
考慮片斷
loop.jsp自定義標籤迭代通過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
當我在調試模式的第一運行,對象全部被創建, 那麼setter是c/d,導致
start = 1
end = 5
if (start < end) {
start++;
return EVAL_BODY_AGAIN;
該循環過程執行4次。
那麼,爲什麼我的名字是汗輸出5次。不應該是4次。
註釋掉'doAfterBody()'中的所有內容。現在打印多少次? 1,對嗎?因爲'doStartTag()'正在打印一次。至少這就是我所猜測的。 – developerwjk 2014-12-05 22:37:31