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.
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");
Or you use
@Inject
Instance<CurrentUserBean> currentUserBeanInstance;
protected void processRequest(...
CurrentUserBean currentUserBean = currentUserBeanInstance.get();
Only Java EE 6
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With