1/7: 这个标签用得怎么时错时对?
循环标签源代码,用于循环输出一个数组的元素,编译后在页面里调用,执行,为什么当第奇数次执行的时候正常显示,第偶数次执行时就报错:
标签代码:
package com.wrox.ch10;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class iterateTag extends TagSupport
{
private int arrayCount=0;
private String[] strings=null;
public int doStartTag(){
strings=(String[])pageContext.getAttribute("strings");
return EVAL_BODY_INCLUDE;
}
public int doAfterBody() throws JspException{
try{
pageContext.getOut().print(" "+strings[arrayCount]+"<br>");
}catch (Exception e){
throw new JspException(e.toString());
}
arrayCount++;
if ( arrayCount>=strings.length)
{
return SKIP_BODY;
}
return EVAL_BODY_AGAIN;
}
}
页面调用:
<%@ taglib prefix="example" uri="WEB-INF/exampleTags.tld"%>
<%
String[] strings=new String[]{"Alpha","Bruce Lee","Omega"};
pageContext.setAttribute("strings",strings);
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>无标题文档</title>
</head>
<body>
<example:iterate>
the string is
</example:iterate>
</body>
</html>
报错信息:
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: java.lang.ArrayIndexOutOfBoundsException: 3
org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:867)
org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:800)
org.apache.jsp.iterate_jsp._jspService(iterate_jsp.java:81)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:133)
javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:311)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:301)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:248)
javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
root cause
javax.servlet.jsp.JspException: java.lang.ArrayIndexOutOfBoundsException: 3
com.wrox.ch10.iterateTag.doAfterBody(iterateTag.java:16)
org.apache.jsp.iterate_jsp._jspx_meth_example_iterate_0(iterate_jsp.java:100)
org.apache.jsp.iterate_jsp._jspService(iterate_jsp.java:71)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:133)
javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:311)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:301)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:248)
javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
note The full stack trace of the root cause is available in the Tomcat logs.
--------------------------------------------------------------------------------
Apache Tomcat/5.0.19