有关于httpsession 的问题

来源:百度知道 编辑:UC知道 时间:2024/09/19 16:39:49
我先建立一个Hashmap对象 然后能否放到session中,怎么放?session.setAttribute("map", map);然后这么拿:
String) session.getAttribute("map");怎么报错,请问有谁知道吗 不太懂

存:
Map map = new HashMap();
map.put("username","admin");
map.put("passwd","123");

session.setAttribute("map", map);

取:

Map user = (Map)session.getAttribute("map");
String username = (String) user.get("username");

你放什么类型,就取出来转换成那个类型,这里你放Map,就取Map,你转换成String取所以错了.

解决方法
一、值放在HashMap里,HashMap再放进session
放:
HashMap map=new HashMap();
map.put("key","your_value");
session.setAttribute("sKey",map);
拿:
HashMap map=(HashMap)session.getAttribute("sKey");
String value=(String)map.get("key");
System.out.println(value);
打印出来就是your_value

二、String 对象直接放进session
放:
String value="your_value";
session.setAttribute("sKey",value);
拿:
String value=(String)session.getAttribute("sKey");
System.out.prin