Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stateful EJB and same session being replicated across clients

I have a stateful EJB that I am using to keep current user information within my application. This EJB is injected into the servlet controller and used to store the last user logged in. However, the session seems to be the same on every single client.

Sample EJB Code:

Stateful
@LocalBean
public class CurrentUserBean {

private string Username;

public void setUser(String un)
{
    Username = un;
}

....

Sample Servlet Code:

public class MainController extends HttpServlet {
       @EJB private CurrentUserBean userBean;

        protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

                HttpSession session = request.getSession();
                String name = session.getAttribute("username");

                userBean.setUser(name);
                ......

Now, when the application is deployed on my server and I have many different people talking to the server from several different clients, the username is always set to the last user that logged in. In other words, it seems as if the stateful session bean is keeping the same state across all clients. This confused me greatly, as I read in the java 6 ee tutorial the following quote from page 247:

In a stateful session bean, the instance variables represent the state of a unique client/bean session. Because the client interacts (“talks”) with its bean, this state is often called the conversational state. As its name suggests, a session bean is similar to an interactive session. A session bean is not shared; it can have only one client, in the same way that an interactive session can have only one user. When the client terminates, its session bean appears to terminate and is no longer associated with the client.

Can someone explain why this is occurring and also explain how to use stateful beans in a proper manner that doesn't keep the same state across all clients?

Thank you.

like image 350
FAtBalloon Avatar asked Dec 16 '11 16:12

FAtBalloon


2 Answers

Although a statefull session bean has a state per user (session actually), the servlet doesn't. By injecting it as you do now a single bean is used by this servlet since it is injected when the servlet is created (probably the bean beloning to the first visitor).

You shouldn't inject the bean, but retrieve it from the context within the processRequest method.

InitialContext ctx= new InitialContext();
CurrentUserBean userBean = (CurrentUserBean)ctx.lookup("CurrentUserBean");
like image 83
Janoz Avatar answered Sep 17 '22 19:09

Janoz


Or you use

@Inject
Instance<CurrentUserBean> currentUserBeanInstance;

protected void processRequest(...
    CurrentUserBean currentUserBean = currentUserBeanInstance.get();

Only Java EE 6

like image 31
Kescha Skywalker Avatar answered Sep 19 '22 19:09

Kescha Skywalker