Tuesday, June 11, 2013

Access a Managed Bean(of an Application) from another(Different Application) Bean ADF

Make an adfjar out of Application1 UI project and add it to the Dependent libraries of Application2 UI project

//Import the bean where you need to refer it
import com.application1.backing.beans.ExampleBean;
import com.utils.JSFUtils;


//Create an object
public class InitBean {

 public static final String BEAN_ID = "initBean";//name used to register
private ExampleBean exampleBean;

    public InitBean() {
        super();
    }
 public String setParams() {
exampleBean = (ExampleBean)JSFUtils.getManagedBeanValue("exampleBean");
// exampleBean this is the name with which it is registered in the adfc-config with session scope of Application1

//Now we can set the values or call methods of ExampleBean from Application2 InitBean
exampleBean.setEmpName("Vijay");
exampleBean.setDeptName("Technology");


}

}



JSFUtils

    /**
     * Convenience method for resolving a reference to a managed bean by name
     * rather than by expression.
     * @param beanName name of managed bean
     * @return Managed object
     */
    public static Object getManagedBeanValue(String beanName) {
        StringBuffer buff = new StringBuffer("#{");
        buff.append(beanName);
        buff.append("}");
        return resolveExpression(buff.toString());
    }



    /**
     * Method for taking a reference to a JSF binding expression and returning
     * the matching object (or creating it).
     * @param expression EL expression
     * @return Managed object
     */
    public static Object resolveExpression(String expression) {
        FacesContext facesContext = getFacesContext();
        Application app = facesContext.getApplication();
        ExpressionFactory elFactory = app.getExpressionFactory();
        ELContext elContext = facesContext.getELContext();
        ValueExpression valueExp =
            elFactory.createValueExpression(elContext, expression,
                                            Object.class);
        return valueExp.getValue(elContext);
    }

No comments: