Why am I getting this error:
java.lang.IndexOutOfBoundsException: Index: 4 , Size: 4
I am not defining anything and have used the same logic on another servlet that is working fine. In my other servlet I am selecting all products, so I used two arraylists: one inside the other. I tried that here but still have the same error. I clearly understand the error but I have no idea how to resolve it in this syntax.
Thank you.
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"));
}
The next JSP page from this servlet is:
<%!
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);
}
%>
you possibly are getting that exception on this line
from your code, this could be the only case. when you call subString() on req index is going out of bound. the best test would be to put a sysout the length of req
EDIT AFTER POSTING THE STACKTRACE
change your java code to this
al = new ArrayList();
while (rs.next()) {
al.add(rs.getString(“product_id”)); // stored in the al at index 0
al.add(rs.getString(“product_name”));// stored in the al at index 1
al.add(rs.getString(“product_description”));// stored in the al at index 2
al.add(rs.getDouble(“product_price”));// stored in the al at index 3
}
heres where its throwing the exception
your list has only 4 elements and you are trying to get the 5th element with above code.
}
change them to