I have recently learnt about stateful and stateless session beans in ejb. I can work along with stateless session beans without any problem (created several applications) but i am finding it hard to implement an application with a stateful session bean.
Here is my scenario : A customer can login using an id and do transactions in his/her account. I want to save the id in to a session bean at the login servlet itself , so that i can retrieve the id from the session to perform transactions.
I know how to work with httpSessions but not with these ejb sessions (stateful beans). Please guide , i want to save the account id to the session (ejb stateful session) and retrieve it back in another servlet.
I have used httpSessions , below is my code:
HttpSession session=request.getSession();
session.setAttribute("accountID", accountid);
But the above is the normal session, how do i use the account session bean to save the id and retrieve it.
Thank you
please refer to this tutorial here , it create a simple Stateful Session Bean (EJB) and use it in a web application context
update thanks to @Gimby:
The key point being that the 'client' (the web application itself in this case) keeps a reference to the stateful bean by sticking it in the session, which keeps the stateful bean active on the server side.
the first thing you need to do is trying to get your EJB from the HttpSession like the following :
MyBean bean = (MyBean) request.getSession().getAttribute("myBean");
then check if the bean is null or not null , if its null create a EJB and add it to the session , like the following :
if(bean == null){
// EJB is not present in the HTTP session
// so let's fetch a new one from the container
try {
InitialContext ic = new InitialContext();
bean = (MyBean)
ic.lookup("java:global/MyBean");
// put EJB in HTTP session for future servlet calls
request.getSession().setAttribute(
"myBean",
bean);
} catch (NamingException e) {
throw new ServletException(e);
}
}
so that way the first time you need the bean you will create it and add it to the session , the second , third , ... etc , you will have it stored in the session .
Hope That Helps .