users@glassfish.java.net

Calling a method in one bean from another

From: <glassfish_at_javadesktop.org>
Date: Wed, 06 Aug 2008 13:15:25 PDT

I'm sure this has been asked many times before, and there is an easy solution, but I want to be able to pass data between two or more beans. I've looked around online quite a bit, but I'm unable to find something that explains this well enough for me to understand. I've got JSF 1.2.

In the simplest case, suppose I have two classes as follows:

public class MyBeana {
 
    private String mynamea;
 
    public Mybeana() {
    // Whatever initialization
    }
 
    public void setMynamea(String mynamea) {
        this.mynamea = mynamea;
    }
 
    public String getMynamea() {
        return mynamea;
    }

// Other methods that may act on the methods above or in MyBeanb.

}
 
public class MyBeanb {
 
    private String mynameb;
 
    public Mybeanb() {
    // Whatever initialization
    }
 
    public void setMynameb(String mynameb) {
        this.mynameb = mynameb;
    }
 
    public String getMynameb() {
        return mynameb;
    }

// Other methods that may act on the methods above or in MyBeana

}

I've tried playing around with FacesContext, but I'm unable to get it to work.

Another idea is to use dependency injection in the faces-config.xml file with something like:

<managed-bean>
   <managed-bean-name>beana</managed-bean-name>
   <managed-bean-class>com.csharp.MyBeana</managed-bean-class>
   <managed-bean-scope>session</managed-bean-scope>
   <managed-property>
      <property-name>beanb</property-name>
      <value>#{beanb}</value>
   </managed-property>
</managed-bean>
 
<managed-bean>
   <managed-bean-name>beanb</managed-bean-name>
   <managed-bean-class>com.csharp.MyBeanb</managed-bean-class>
   <managed-bean-scope>session</managed-bean-scope>
</managed-bean>

but I don't know what syntax to use. Basically, I could have pages with tags such as:

<h:inputText value="#{beana.mynamea}">
<h:inputText value="#{beanb.mynameb}">

plus many others, and want to be able to access the methods of one bean from the other.

The link http://wiki.apache.org/myfaces/AccessingOneManagedBeanFromAnother gives some useful information, but it's not very clear, and a simple worked example would be a great help.

I would most appreciate some help with this.

Christopher Sharp
[Message sent by forum member 'csharpdotcom' (csharpdotcom)]

http://forums.java.net/jive/thread.jspa?messageID=291972