java – 如何在servlet线程中获取新的有状态会话bean?

我正在试验EJB3

我想将一个有状态会话bean注入一个servlet,这样每个访问servlet的用户都会获得一个新的bean.

显然,我不能让bean成为servlet的实例变量,因为它将被共享.并且不允许显着地注入局部变量.

我可以使用new运算符来创建bean,但这似乎不是正确的方法.

有没有正确的方法来做到这一点?看起来我想要做的事情是相当简单的,毕竟,我们希望每个新客户都能找到一个空的购物车.

解决方法

您无法使用new来获取新的SFSB.

您通常使用InitialContext查找新的.

MyBean bean = (MyBean) new InitialContext().lookup( name );

然后,您将获得对可以在请求中重用的特定SFSB的引用.

从this answer开始:

You should not typically inject SFSB,
unless it is into another SFSB or into
a Java EE client. You should use @EJB
on the referencing class (e.g. your
servlet) to declare the ejb-ref and
then do a JNDI lookup in the code to
obtain the instance. This instance
could then be placed directly in your
Http session.

有关SFSB的更多信息,您可能对我的其他答案感兴趣:

> Stateful EJBs in web application?
> Java: Tracking a user login session – Session EJBs vs HTTPSession
> Correct usage of Stateful Beans with Servlets

希望能帮助到你.

dawei

【声明】:唐山站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。