Java MySQL IndexOutOfBounds错误

Tra*_*Can 1 java mysql jsp servlets

为什么我收到此错误:

java.lang.IndexOutOfBoundsException:索引:4,大小:4

我没有定义任何东西,并在另一个工作正常的servlet上使用相同的逻辑.在我的其他servlet中,我选择了所有产品,所以我使用了两个arraylists:一个在另一个内部.我试过这里,但仍然有同样的错误.我清楚地理解错误,但我不知道如何在这种语法中解决它.

谢谢.

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"));
    }
Run Code Online (Sandbox Code Playgroud)

此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);
    } 
    %>
Run Code Online (Sandbox Code Playgroud)

Per*_*ror 5

你可能在这条线上得到了这个例外

int product_id =Integer.parseInt(req.substring(req.lastIndexOf("/")+1));
Run Code Online (Sandbox Code Playgroud)

从您的代码中,这可能是唯一的情况.当你在req上调用subString()时索引越界.最好的测试是将sysout放入req的长度

发布STACKTRACE后编辑

将您的java代码更改为此al = new ArrayList();
while(rs.next()){al.add(rs.getString("product_id")); //存储在al 0索引al.add(rs.getString("product_name")); //存储在al 1索引al.add(rs.getString("product_description")); //存储在索引2的al ald(rs.getDouble("product_price")); //存储在索引3的al中}

继承人抛出异常的地方

 line1:  product_id = productList.get(1).toString(); 
 line2:               product_name = productList.get(2).toString(); 
 line3:               product_description = productList.get(3).toString(); 
 line4               product_price = (Double) productList.get(4); /// its going indexoutfbound    here
Run Code Online (Sandbox Code Playgroud)

你的列表只有4个元素,你试图用上面的代码获得第5个元素.}

改变他们

  product_id = productList.get(0).toString(); 
                product_name = productList.get(1).toString(); 
                product_description = productList.get(2).toString(); 
                product_price = (Double) productList.get(3);
} 
Run Code Online (Sandbox Code Playgroud)