Search code examples
javajsfjakarta-eejsf-2managed-bean

Modifying a private object property of a managed bean accessed as a managed property from another managed bean


Trying to add a functionality to our JSF 2 application to list active users (who have an active session) and for this I decided to use an application scoped managed bean and store the list of users, adding each by the time of a successful login. Then I would access the active user list (stored on the application scoped managed bean) from a jsf page - only if I could figure out how to resolve the following problem:

The application scoped bean : AppBean.java

@ManagedBean(name = "appBean")
@ApplicationScoped
public class AppBean implements java.io.Serializable {

    private List<User> connectedUsers = new ArrayList<User>();

    public AppBean() {
    }

    public List<User> getConnectedUsers() {
        return connectedUsers;
    }

    public void setConnectedUsers(List<User> connectedUsers) {
        this.connectedUsers = connectedUsers;
    }  
}

the Login Bean:

@Named(value = "loginBean")
@SessionScoped
public class LoginBean implements Serializable {

    @ManagedProperty("#{appBean}")
    private AppBean appBean;

    private User userInSession;

    public LoginBean() {
    }

    public String authenticate() {
        if (this.authClearsOut()) {
            if (appBean != null)
                appBean.getConnectedUsers().add(userInSession);
            else System.out.println("appBean = null !!!!");
            return "/next_screen.xhtml?redirect=true";
        }
        else return "/login.xhtml?authentication=failed";
    }

    public AppBean getAppBean() {
        return appBean;
    }

    public void setAppBean(AppBean appBean) {
        this.appBean = appBean;
    }
}

Now there are two problems here: 1) the appBean is null unless I change line 6 of the LoginBean.java to private AppBean appBean = new AppBean(); 2) User userinSession is never added to (List) connectedUsers.

What's wrong here?


Solution

  • The JSF @ManagedProperty annotation works in JSF @ManagedBean only, not in CDI @Named.

    Change the LoginBean to be managed by JSF @ManagedBean instead, or change the AppBean beans to be managed by CDI @Named and then use @Inject instead of @ManagedProperty.