views:

59

answers:

1

Hello there! We're learning EJB 3.0 in school and we're trying to determine best practice for a problem our teacher has posed. We don't use Spring yet.

The problem is as follows: Create an EJB that keeps track of the time the bean was last called by the same user (call the first user John) and displays this in a web (servlet) context. If a different user (call him Bill) calls the bean it shows the last time Bill called the bean, which is different from the time when John last did.

Now, we can do this using the session object from the servlet Request. This would assign each session an instance of the EJB and not take advantage of dependency injection. Like this (pseudocode):

doGet{

   timeManagerEJB = session.getattribute("localTimeEJB");

   if(timeManagerEJB == null) { 

timeManagerEJB = InitialContext.lookup("path...");

session.setAttribute("localTimeEJB", timeManagerEJB);

}

}

Is this the best way to do it or is there a function built into the EJB framework to handle multiple instances of a stateful EJB, possibly taking advantage of dependency injection?

+1  A: 

Is this the best way to do it or is there a function built into the EJB framework to handle multiple instances of a stateful EJB, possibly taking advantage of dependency injection?

You must not inject a Stateful Session Bean into a stateless object such as a Stateless Session Bean or a Servlet that may be shared by multiple concurrent client, you have to use JNDI in such cases (and put the reference into the http session).

Pascal Thivent