简体   繁体   中英

Class cast exception when i try to cast getAttribute from the session object?

I know it is possible without any exceptions being thrown but how can i cast this object/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");
            }

Shopping cart cast throws class cast exception cannot cast string to model type lessonSelection. Any help would be much appreciated.

You are putting a String object inside session with session.setAttribute("cart", username); but you are later trying to cast this String to ShoppingCart . It is normal that String can not be casted to ShoppingCart so it gives a ClassCastException .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM