Java 在httpSession中存储扩展对象
在下面的代码中,learning是一个学习实例,我想将其保存为http会话的原样Java 在httpSession中存储扩展对象,java,session,tomcat,servlets,Java,Session,Tomcat,Servlets,在下面的代码中,learning是一个学习实例,我想将其保存为http会话的原样 learning = new Learning(learningContext); HttpSession webSession = request.getSession(); webSession.setAttribute("learning", learning); Learning learnTest = webSession.getAttribute("learning"); 当我运行下面的代码时,我得到
learning = new Learning(learningContext);
HttpSession webSession = request.getSession();
webSession.setAttribute("learning", learning);
Learning learnTest = webSession.getAttribute("learning");
当我运行下面的代码时,我得到:
Incompatible types
Learning learnTest = webSession.getAttribute("learning")
required: Learning
found: Object
我可以将非泛型对象保存到会话中吗?还有其他方法可以实现这一点吗?您需要像这样投射对象-
Learning learnTest = (Learning) webSession.getAttribute("learning")
您需要强制转换为特定类型,因为getAttribute的返回类型是Object。您需要像这样强制转换对象-
Learning learnTest = (Learning) webSession.getAttribute("learning")
您需要强制转换为特定类型,因为getAttribute的返回类型是Object。HttpSession.getAttribute的javadoc说明: java.lang.Object getAttribute(java.lang.String名称) 返回在此会话中使用指定名称绑定的对象,如果名称下没有对象绑定,则返回null 我的意思是,通过构造,它总是返回一个简单的对象。正如您所知道(或希望)的,您已经在那里放置了一个
学习
,您只需执行一个显式转换:
Learning learnTest = (Learning) webSession.getAttribute("learning");
HttpSession.getAttribute的javadoc说明: java.lang.Object getAttribute(java.lang.String名称) 返回在此会话中使用指定名称绑定的对象,如果名称下没有对象绑定,则返回null 我的意思是,通过构造,它总是返回一个简单的对象。正如您所知道(或希望)的,您已经在那里放置了一个
学习
,您只需执行一个显式转换:
Learning learnTest = (Learning) webSession.getAttribute("learning");
您是否尝试过.toString()或casting之类的解决方法?您是否尝试过.toString()或casting之类的解决方法?