I am coming to Java from Rails and PHP, so my thinking here may be tainted. I would like to implement a login system similar to ones I have done in my other systems (I understand you can manage login etc using the built in properties of Java EE, I just want to understand how I could do this manually and share objects amongst beans.)
With rails or php it is easy to maintain a session variable that holds the id of a logged in user. Then a global variable in PHP, or a property on the applicationController in rails can be pre-loaded with the user object, enabling it be available in all controllers/pages. That way the logged in status of the user and other parameters are easily accessible to all pages/controllers.
I don't know how to do a similar thing using JSF.
I know how to build a user object using JPA, and then create a managed bean with session scope that holds a reference to the user object after logging in using a loggin method from a login form. That part I understand:
@ManagedBean
@SessionScope
public class LogginController {
// inject persistence context, or use EJB to do actual loading etc
private User currentUser; //JPA Entity
void loginAction() {
// action from login form
// authenticates user and loads user object into currentUser property
Where I get stuck, is that although the managed bean that contains the currentUser property has session scope, how would I access that property in other managed beans to get the current user? Managed beans seem to exist in isolation from each other.
Is the following code acceptable?
@ManagedBean
public class SomeOtherBean {
@ManagedProperty
LoginController loginController;
public void someOtherMethod() {
User myUser = loginController.getCurrentUser();
//
// etc
Would the class having the bean injected also have to have SessionScope too? Is this the wrong approach, would I need to manually set the session using the underlying ServletContext so that the user was accessible in other beans (i.e. save the id of the logged in user in the session, and then reload the user after accessing the user id session variable in different beans)?
Am I going about this all wrong? Is there an easier way I am missing.