I have a login.java servlet and, as its name says, it provides login facilities to my web application.
I'm a newbie and I'm using EJB 3.1 and EE 6. In my LoginBean.java EBJ I have a no-arguments constructor and another one that has some parameters (email, password, etc).
At certain point in the servlet code I have the calling to instantiate my EJB:
@EJB LoginBean loginBean;
I'd like to know if it's possible (and how) to call the other constructor instead of the zero-arguments one.
Thanks a lot.
Cheers.
You don't want to do that. The one and same servlet is shared among all users, so the EJB is also shared among all users. You don't want to store user-specific data as instance variable of the servlet or EJB class. It would be shared among all webpage visitors.
Rather move the arguments to a EJB method which you invoke in the doPost()
method of the login servlet.
User user = loginBean.login(username, password);
and then store this in the HTTP session when it went successful
request.getSession().setAttribute("user", user);
so that the rest of your webapp can intercept on this to determine if the user is logged in or not.
if (request.getSession().getAttribute("user") != null) {
// User is logged in.
} else {
// User is not logged in.
}
I 100% agree with BalusC. In addition to his answer I would like to add that you normally* never explicitly reference the constructor of an EJB bean, even if doing so would theoretically make sense (e.g. when passing in some dependencies, or some configuration parameter).
EJB beans are managed objects and what you are getting in your @EJB annotated field is not the actual object but a stub
(proxy). The actual object instance to which the stub points is most likely constructed long before you get this stub to it and also very likely comes from a pool.
(*)Some kind of units tests may be an exception to this rule.