【发布时间】:2012-09-14 07:10:42
【问题描述】:
为什么会出现这个错误:
java.lang.IndexOutOfBoundsException:索引:4,大小:4
我没有定义任何东西,并且在另一个运行良好的 servlet 上使用了相同的逻辑。在我的另一个 servlet 中,我选择了所有产品,所以我使用了两个数组列表:一个在另一个里面。我在这里尝试过,但仍然有同样的错误。我清楚地理解了这个错误,但我不知道如何用这种语法解决它。
谢谢。
ConnectionPool pool = ConnectionPool.getInstance();
Connection connection = pool.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
int product_id =Integer.parseInt(req.substring(req.lastIndexOf("/")+1));
ArrayList al = null;
String query = "select * from Product where product_id="+product_id;
try {
ps = connection.prepareStatement(query);
rs = ps.executeQuery(query);
while (rs.next()) {
al = new ArrayList();
al.add(rs.getString("product_id"));
al.add(rs.getString("product_name"));
al.add(rs.getString("product_description"));
al.add(rs.getDouble("product_price"));
}
此 servlet 的下一个 JSP 页面是:
<%!
String product_id="";
String product_name="";
String product_description="";
double product_price = 0;
ArrayList productList=null;
%>
<%
if(request.getAttribute("productList")!=null && request.getAttribute("productList")!="") {
productList = (ArrayList)request.getAttribute("productList");
product_id = productList.get(1).toString();
product_name = productList.get(2).toString();
product_description = productList.get(3).toString();
product_price = (Double) productList.get(4);
}
%>
【问题讨论】:
-
可能
req以/结尾,所以req.substring(req.lastIndexOf("/")+1)会出错。 -
你能发一个stacktrace吗?
-
如果你不知道是哪一行抛出了令人费解的异常,它们通常会更清楚。因此,您不仅应该记录他的消息,而且至少应该记录最后一个堆栈跟踪条目的行。
-
a) 将您的代码从 jsp 移出到适当的 java 类中。 b)您向我们展示的代码块中未引发异常。可能有一些 jsp 标记,您正在尝试获取 al[4]。
-
你可能是对的,张贴在下一个 jsp 页面上方采取这些东西