How do I obtain a new stateful session bean in a servlet thread?

我的梦境 提交于 2020-01-01 05:35:07

问题


I'm experimenting with EJB3

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.

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.

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.


回答1:


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

What you typically do is to lookup a new one using the InitialContext.

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

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

From 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.

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

Hope it helps.



来源:https://stackoverflow.com/questions/2833457/how-do-i-obtain-a-new-stateful-session-bean-in-a-servlet-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!