2011-02-18 60 views
5

我正在开发一个使用Struts 2和Spring 3后端的web应用程序。我使用Spring aop:代理bean来处理会话bean,而不是Struts 2 SessionAware接口。一切正常,直到我有一个在Struts ExecAndWait拦截器下运行的Action。因为这个拦截器实际上在一个单独的线程下运行我的动作,当我试图访问我的代理会话bean时,我得到一个BeanCreationException/IllegalStateException异常。在这种情况下,我能否获得会话bean的另一种“春天方式”?访问Spring Session作用域代理bean

Regards

+0

当然,当您的子线程需要访问该bean时,会话可能已被用户销毁。可能需要重新审视您的范围。 – 2013-10-29 21:24:56

回答

0

您可以使用Spring实现您自己的ExecAndWait拦截器。您也可以将此操作的管理/创建委派给Spring。后面的细节在S2弹簧插件文档中。

3

Execute and Wait Interceptor文档

重要:由于动作将是在一个单独的线程中运行,则无法使用ActionContext中,因为它是一个ThreadLocal。这意味着如果您需要访问会话数据,则需要实现SessionAware而不是调用ActionContext.getSession()。

会话scoped-beans的问题在于它们依赖于由RequestContextListenerRequestContextFilter设置的线程本地属性。但后者允许你设置非常有趣的threadContextInheritable标志......

如果你的ExecAndWait拦截器为它所服务的每个请求创建一个新的线程,可继承的线程本地应该将会话作用域的bean传播给子线程。但是,如果Struts使用线程池(更有可能,您没有使用Struts2很长时间)来处理这些请求,这将会产生非常意想不到的危险结果。你可以尝试这个标志,也许它会做到这一点。

0

您可以使用​​(Holder类以线程绑定的RequestAttributes对象的形式公开Web请求),以使会话作用域的代理bean可用于子线程。

定义自定义ExecuteAndWait拦截并在doIntercept方法使用下面的静态方法从RequestContextHolder

公共静态无效setRequestAttributes(RequestAttributes属性,布尔可继承

绑定给定RequestAttributes到当前线。

参数: 属性 - 在RequestAttributes暴露,或空重置线程绑定的语境 可继承 - 是否暴露RequestAttributes为可继承的子线程(使用的InheritableThreadLocal)

样品代码

public class CustomExecuteAndWaitInterceptor extends ExecuteAndWaitInterceptor { 

    @Override 
    protected String doIntercept(ActionInvocation actionInvocation) throws Exception { 
     RequestAttributes requestAtteiAttributes = RequestContextHolder.getRequestAttributes(); //Return the RequestAttributes currently bound to the thread. 
     RequestContextHolder.setRequestAttributes(requestAtteiAttributes, true); 
     //do something else if you want .. 
     return super.doIntercept(actionInvocation); 

    } 
} 
相关问题