【问题标题】:Spring MVC Application - How do I set a session scoped bean valueSpring MVC 应用程序 - 如何设置会话范围的 bean 值
【发布时间】:2010-01-25 14:33:33
【问题描述】:

在我的应用程序中,我需要在一个屏幕上收集信息,然后在下一个屏幕上显示。

我已选择将此信息存储在一个范围设置为会话的 bean 中(它将在初始数据收集屏幕之后的其他几个屏幕中使用)

Manager配置如下:

 <bean name="/springapp.htm" class="foo.bar.controller.springcontroller">
        <property name="sessionBeanManager" ref="sessionBeanManager" />
    </bean>

bean配置如下:

<bean id="sessionBean" class="foo.bar.sessionBean" scope="session">
    <aop:scoped-proxy/>
   <property name="beanValue" value="defaultValue" />
</bean>

<bean id="sessionBeanManager" class="foo.bar.sessionBeanManagerImpl">
    <property name="sessionBean" ref="sessionBean"/>
</bean>

我正在使用

在 jsp 页面上输出
<c:out value="${sessionBean.beanValue}"></c:out>

但是每当我加载页面时,值都是空的?

在我看来,bean 加载正常,但没有填充值,这导致我认为会话 bean 没有被填充或者 bean 没有被创建为会话 bean?

【问题讨论】:

  • 如何创建 sessionBean?
  • 您的示例中没有 sessionBean 的 bean 定义 - 它在哪里?
  • 会话 bean 现在可见

标签: spring spring-mvc spring-aop


【解决方案1】:

您可以在 jsp 中的 EL 中使用以下语法引用 Spring 会话 bean。

${sessionScope['scopedTarget.messageUtil'].flashMessages}

在这个 bean 上调用 getFlashMessages()

<bean id="messageUtil" class="mypackage.MessageUtilImpl" scope="session">
    <aop:scoped-proxy proxy-target-class="false"/>
    <property name="messageSource" ref="messageSource" />
</bean>

【讨论】:

  • 如果您想了解更多信息,我在几周前发布了一篇关于它的博客文章。 digitaljoel.nerd-herders.com/2010/11/01/…
  • 我读到了,并且能够让您的方法发挥作用。但是起初我遇到了麻烦,因为在使用之前,spring容器实际上并没有初始化messageUtil。您如何建议预先播种消息,以便在有人首次登录时显示?
  • 一旦他们登录,他们就有一个很好的会话,所以你应该能够将 messageUtil 注入控制器或其他东西并将消息放入其中。真正的困难是当他们没有登录并且您想要添加诸如登录失败之类的消息时。我们最终处理这个案子的方式略有不同。
【解决方案2】:

除非您先将 Spring bean 添加到模型中,否则 Spring bean 在视图(在您的情况下为 JSP)中不可见。

您必须将 sessionBean 添加到控制器中的模型中,以使其可用于视图。

model.addAttribute("sessionBean", sessionBean);

【讨论】:

  • 如何访问控制器中的 bean?
  • 你必须注入它。或者通过已经注入的 sessionBeanManager 获取它。
  • 范围代理可以可见。见:stackoverflow.com/a/3047273/366073
猜你喜欢
  • 2015-12-09
  • 2011-07-01
  • 1970-01-01
  • 2011-02-23
  • 2012-05-21
  • 1970-01-01
  • 2013-02-26
  • 1970-01-01
  • 2012-10-31
相关资源
最近更新 更多