views:

386

answers:

1

Hi all,

I have a J2ee application consisting of 1 web module and 1 EJB module. Inside my EJB module I have a stateful session bean containing my business logic.

What I would like is:

When a user logs in to 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.

At the moment a session is being created in the web tier as expected but I am unsure about how to map the session in the web tier to a new EJB session each time. Currently I am invoking my EJB from my Servlet meaning that only 1 instance of the bean is being created. I am trying to get a 1-1 mapping between web sessions and sessions in my EJB layer.

I know this could be achived easily using application clients but any advice / design patterns on how I could achive this in the web tier would be greatly appreciated.

Cheers Karl

+1  A: 

Stateful Sessions are not always a good choice, sometimes using persistence to a DB is easier.

In the servlet, as process a request from a user, obtain the "handle" to your SFSB. Put that "handle" into your HttpSession. Now when the next request for that user arrives you have the handle ready.

With EJB 3.0 do it like this.

Declare the bean reference with @EJB at class scope, this sets up the reference you'll use later

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

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

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

Store the interface in the HttpSession object to retrieve as needed

session.setAttribute(“counter”, counter);
djna
+1. There is one thing that newbies often do not think of - they declare the EJB reference (counter in your example) as a member of the servlet, thus making it a singleton effectively.
Vineet Reynolds
Thanks, tried to make that more clear.
djna