Java EE Session Management Between Web & EJB Tiers

I have a Java EE application made up of 1 web module and 1 EJB module. Inside my EJB module, I have a stateful session bean that contains my business logic.

I would like to:

When a user logs into my web application and creates a new session in the web tier, I want that user to be assigned an instance of my session bean.

Currently, the session is being created in the web tier as expected, but I'm not sure how to map the session in the web tier to a new EJB session each time. I am currently calling my EJB from my servlet which means only 1 bean instance is created. I am trying to get 1-1 mapping between web sessions and sessions in my EJB layer.

I know this can be easily achieved with application clients, but any advice / design patterns on how I could achieve this in the web tier would be greatly appreciated.

+2


source to share


1 answer


Stateful sessions are not always a good choice, sometimes it is easier to use database persistence.

In the servlet, how the request from the user is processed, get the "handle" to your SFSB. Place this "handle" in your HttpSession. Now, when the next request comes in for that user, you have a handle ready.

With EJB 3.0, do it like this.

Declare a link bean with @EJB in class scope, this sets up a link that you will use later

@EJB 
(name="CounterBean", beanInterface=Counter.class)
public class MyStarterServlet

      



When processing request: EJB access using JNDI and declared bean name, please note that this code is in your doGet () and / or doPost () method, the "counter" variable must be local (on stack) as the servlet object shared between potentially many requests at the same time.

Context ctx = new InitialContext(); 
Counter counter = (Counter)
ctx.lookup("java:comp/env/CounterBean");
counter.increment();

      

Store the interface in an HttpSession object to retrieve as needed

session.setAttribute("counter", counter);

      

+3


source







All Articles