DarkLazar
DarkLazar

Reputation: 83

How to pass property of a java bean to another java bean?

I am trying to take a value from one managed bean to another. I have a loginbean which gets the username and I need to take that value and put it into another managed bean sidebarbean. I am using JSF and thought i could go something like #{sidebarbean.setUserName(loginbean.username)} but this does not work. Any suggestions?

Following your suggestion

@ManagedBean(name = "sidebarbean")
@SessionScoped
public class SideBarBean {
    private ArrayList myContacts = new ArrayList();
    private String user;
    @PersistenceContext
    private EntityManager em;
    @Resource
    private UserTransaction utx;

    public SideBarBean() {

    }

    public ArrayList getMyContacts() {
        myContacts.clear();
        List<Contacts> list = em.createNamedQuery("Contacts.findByUsername")
            .setParameter("username", user).getResultList();
        for (Contacts c : list) {
            myContacts.add(c.getContact());
        }
        return myContacts;
    }

    public void setMyContacts(ArrayList myContacts) {
        this.myContacts = myContacts;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }
}

@ManagedBean(name = "loginbean")
@SessionScoped
public class LoginBean {
    @PersistenceContext
    private EntityManager em;
    @Resource
    private UserTransaction utx;
    @ManagedProperty(value="#{sidebarbean}")
    private SideBarBean sbb;
    private String username;
    private String password;
    private Boolean verified = false;
    private Boolean authFail = false;

    public LoginBean() {
    }

    public void update(){
        sbb.setUser(username);
    }

I get "Unable to create managed bean loginbean. The following problems were found: - Property sbb for managed bean loginbean does not exist. Check that appropriate getter and/or setter methods exist."

Upvotes: 2

Views: 1445

Answers (1)

HRgiger
HRgiger

Reputation: 2790

You can use @ManagedProperty annotation then you can access to same instance of SideBarBean.

@ManagedBean(name="loginbean")
public class LoginBean{

 @ManagedProperty(value="#{sidebarbean}")
 private SideBarBean sidebarbean;

 public void update(){

  sidebarbean.setUserName("xxxx");

 }

}

Upvotes: 2

Related Questions