我正在Web应用程序中使用会话,问题是当我在一个会话中存储一个值时,使用另一个会话存储“最大”索引来跟踪ArrayList中保存的元素数。
ArrayList<String> list = new ArrayList<String>();
int a = (int) request.getSession().getAttribute("max");
System.out.print(a); // here a = 0 the first time
list.add(request.getParameter("articolo")); // add a String value which in this case is a name of a product in my webapp
System.out.print((String) list.get(a)); // the just stored value gets printed
request.getSession().setAttribute("carrello" + a, list.get(a)); // add the just stored value in a session which is "carrello 0 " in this case
request.getSession().setAttribute("max", a+1);// increment the max index in session max
//list.clear(); i've also tried to do this to prevent the error
request.getSession().setAttribute("messaggio","Prodotto aggiunto al carrello!"); // just a message saying " Product added to cart "
response.sendRedirect("visualizzaTab.jsp"); // redirect to a jsp page
我收到IndexOutOfBoundsException,向您保证在打印“购物车”会话中存储的每个产品后,最大会话值将设置为0。如果您需要更多代码,请在下面注释
答案 0 :(得分:0)
由于以下几行,您的列表将始终为空:
ArrayList<String> list = new ArrayList<String>();
但是,因为您在以下行中将“ max”会话属性修改为1:
request.getSession().setAttribute("max", a+1);// increment the max index in session max
由于列表为空,因此任何后续请求到达以下代码行时,都会发生IndexOutOfBoundsException:
System.out.print((String) list.get(a)); // the just stored value gets printed