IndexOutOfBoundsException при работе с сессиями - PullRequest
0 голосов
/ 05 июня 2019

Я работаю с сеансом в веб-приложении, проблема в том, что я сохраняю значение в сеансе, используя другой сеанс для хранения индекса "max", чтобы отслеживать количество элементов, сохраненных в 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 после того, как я распечатаю каждый продукт, сохраненный в сеансе «корзины». Если вам нужно больше кода, просто прокомментируйте ниже

1 Ответ

0 голосов
/ 05 июня 2019

Ваш список всегда будет пустым из-за следующей строки:

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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...