【问题标题】:Storing an extended object in the httpSession在 httpSession 中存储扩展对象
【发布时间】:2016-06-17 21:50:27
【问题描述】:

在下面的代码中,learning 是一个我想保存到 http 会话的 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

我可以将非通用对象保存到会话中吗?还有其他方法可以实现吗?

【问题讨论】:

  • 您是否尝试过任何解决方法,例如 .toString() 或强制转换?

标签: java session tomcat servlets


【解决方案1】:

你需要像这样投射对象 -

Learning learnTest = (Learning) webSession.getAttribute("learning")

您需要转换为特定类型,因为 getAttribute 的返回类型是 Object。

【讨论】:

    【解决方案2】:

    HttpSession.getAttribute 的 javadoc 说:

    java.lang.Object getAttribute(java.lang.String name) 返回此会话中与指定名称绑定的对象,如果该名称下没有绑定任何对象,则返回 null。

    我的意思是通过构造它总是会返回一个单纯的对象。如您所知(或希望)您已将Learning 放在那里,您只需要进行显式转换:

    Learning learnTest = (Learning) webSession.getAttribute("learning");
    

    【讨论】:

      猜你喜欢
      • 2011-08-11
      • 1970-01-01
      • 2011-01-07
      • 2021-10-11
      • 2018-07-03
      • 2016-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多