【问题标题】:IndexOutOfBoundsException while working with sessions处理会话时出现 IndexOutOfBoundsException
【发布时间】:2019-06-05 16:40:04
【问题描述】:

我在 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。如果您需要更多代码,请在下方评论

【问题讨论】:

    标签: java jsp session arraylist


    【解决方案1】:

    由于以下行,您的列表将始终为空:

    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
    

    【讨论】:

      猜你喜欢
      • 2015-03-17
      • 1970-01-01
      • 2014-06-10
      • 2014-07-28
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多