How to get a new session with bean state in servlet thread?

I am experimenting with EJB3

I would like to enter a session with a bean state in the servlet so that every user who gets into the servlet gets a new bean.

Obviously, I cannot allow the bean to be an instance variable for a servlet, as this will be common. A apparantly injection of local variables is not allowed.

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

Is there a proper way to do this? It seems that what I'm trying to do is pretty simple, after all, we want every new customer to find an empty cart.

+6
java java-ee dependency-injection servlets
source share
1 answer

You cannot use new to get a new SFSB.

What you usually do is lookup new using InitialContext .

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

Then you get a link to a specific SFSB, which you can reuse for different requests.

From this answer :

Normally you should not inject SFSB unless it is in another SFSB or in the Java EE client. You must use @EJB in the reference class (e.g. your servlet) to declare ejb-ref and then do a JNDI lookup in the code to get an instance. This instance can then be placed directly in your Http session.

For more information about SFSB, you may be interested in the following answers from me:

Hope this helps.

+14
source share

All Articles