简体   繁体   English

如何将会话对象放入哈希图中

[英]How to get session object into a hashmap

I am saving a HashMap into a session like so: 我将HashMap保存到如下session

HashMap<Integer, Cart> cart = new HashMap<>();
            cart.put(id, new Cart(product.getName(), product.getPrice(), 1, product.getImage()));
            session.setAttribute("cart", cart);

But how am I supposed to get it out of the session back into a HashMap ? 但是我应该如何将其从会话中返回到HashMap呢?

I am aware that the session data is stored as an object but do not know how to get it into a HashMap 我知道会话数据存储为对象,但不知道如何将其放入HashMap

I've tried: 我试过了:

HashMap<Integer, Cart> cart = session.getAttribute("cart");

But it says cannot from Object to HashMap 但是它说cannot from Object to HashMap

getAttribute returns Object getAttribute返回Object

public Object getAttribute(String name)

You can cast Map as, 您可以将Map转换为

HashMap<Integer, Cart> cart = (HashMap<Integer, Cart>) session.getAttribute("cart");

session stores the values as Object. 会话将值存储为对象。 You need to type cast when retrieving from session to the type of object you stored in session. 从会话检索到存储在会话中的对象类型时,需要键入强制类型转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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