如何在servlet线程中获取新的有状态会话bean? [英] How do I obtain a new stateful session bean in a servlet thread?

查看:154
本文介绍了如何在servlet线程中获取新的有状态会话bean?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在试验EJB3

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

I would like to inject a stateful session bean into a servlet, so that each user that hits the servlet would obtain a new bean.

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

Obviously, I can't let the bean be an instance variable for the servlet, as that will be shared. And apparantly injecting local variables isn't allowed.

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

I can use the new operator to create a bean, but that doesn't seem the right approach.

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

Is there a right way to do this? It seems like what I'm trying to do is fairly straightforward, after all, we would want each new customer to find an empty shopping cart.

推荐答案

您不能使用 new 来获取新的SFSB。

You can't use new to get a new SFSB.

你通常做的是查找使用 InitialContext

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

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

You get then a reference to a specific SFSB that you can reuse across requests.

来自这个答案


你通常不应该注入SFSB,
除非它进入另一个SFSB或
a Java EE客户端。你应该在引用类(例如你的
servlet)上使用@EJB
来声明ejb-ref和
然后在代码中进行JNDI查找以获得实例
。然后可以将此实例
直接放在
Http会话中。

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的更多信息,可能对我的其他答案感兴趣:

For more information about SFSB, you might be interested in these other answers from me:

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

希望有所帮助。

这篇关于如何在servlet线程中获取新的有状态会话bean?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆