当我尝试从会话对象转换getAttribute时,类强制转换异常?

时间:2014-12-15 21:13:38

标签: java

我知道有可能没有任何异常被抛出,但我怎么能转换这个对象/ bean:

public class ShoppingCart {
private HashMap<String, Item> items;
private String owner;

public ShoppingCart(String owner) {
    items = new HashMap<String, Item>();
    this.owner = owner;
}

public class Servlet extends HttpServletRequest request

         if (action.equals("/addItem")) {
                //if()
                String Id = request.getParameter("itemId");
                ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");
                int quantity = Integer.parseInt(request.getParameter("quantity").toString());
                Item item = this.stock.getItem(Id);
                cart.addItem(item, quantity);
                dispatcher = this.getServletContext().getRequestDispatcher(action = "/CartView.jspx");
            }

购物车投掷抛出类强制转换异常无法将字符串转换为模型类型的lessonSelection。 任何帮助将非常感激。

1 个答案:

答案 0 :(得分:0)

您将String对象放入与session.setAttribute("cart", username);的会话中,但您稍后尝试将此String转换为ShoppingCartString无法投放到ShoppingCart是正常的,因此它会提供ClassCastException