I create an ArrayList based on ProductData class on my JSP, this list represents as a shopping cart.
ArrayList<ProductData> cartList = new ArrayList<ProductData>();
ProductData data = new ProductData(productId, productName, productPrice, productAmmount);
cartList.add(data);
After that, I’m storing my ArrayList to JSP session, cause I don’t want my ArrayList lost when I leave this page.
session.setAttribute("cartList", cartList);
On the other section, I get the session and convert it as an ArrayList of ProductData
(I check if the session is null or not for sure)
ArrayList<ProductData> cartList = session.getAttribute("cartList") == null ? new ArrayList<ProductData>() : (ArrayList<ProductData>)session.getAttribute("cartList");
It works well on the first run. But, every time I changes the code on my page (and I’m not modifying my class declaration), the servlet thows an error: java.lang.ClassCastException: org.apache.jsp.MCPatisserie.cart_jsp$1ProductData
My question is: is this a good method to implement a class on java servlet page?
Is this error caused by recompilation of the servlet page and the session object didn’t match with my ArrayList anymore?
Thanks in advance. 🙂
Each time you change your JSP, the container recompiles it to a new Java source file, and recompiles this new Java source file to a new class. It seems you have defined a Java class inside the JSP. So this class is also regenerated and recompiled. So the object in the session has a class that is not the same as the one recreated.
You shouldn’t have Java code in JSPs. And definitely not class definitions. ProductData should be defined in its own .java file, like any other class.