Multiple Managed Beans

Does it make sense to have multiple managed beans with a JSF app?
Is there a tutorial for doing this in JSC?
I can see the need for a larger app to have many managed beans at the request level and/or session level.
If there isn't a way to do this then why are the beans called RequestBean1, SessionBean1, etc... How do I add RequestBean2?
Thanks,
Brent

If you don't want to use managed property injection, then you can also use FacesContext#getELContext() ExternalContext#getRequestMap(), getSessionMap() or getApplicationMap() to find the managed beans in the desired scope. Also see this article part: [http://balusc.blogspot.com/2006/06/communication-in-jsf.html#AccessingAnotherManagedBean].

Similar Messages

  • Rendered Property calling managed bean Multiple Times

    Hi
    We have a problem within a command button in a jspx, which includes a rendered tag which references a managed bean method via EL.
    e.g.
    rendered="#{PERUserInfo.trainee}"
    When I debug the jspx, the PERUserInfo.trainee method is called 4 times instead of once.
    We have noticed similar findings when using managed bean methods via the rendered property. i.e. calls getters multiple times.
    Any idea why this is happening?
    We are using JDeveloper v10.1.3, JHS v10.1.3 SU1.
    All comments appreciated.
    Cheers
    Denis

    Denis,
    There can be many reasons why your bean method is called multiple times; but I would consider this perfectly normal in any JSF application considering all the lifecycles and (possible) Partial Page Rendering that happens.
    The question is, by the way, more appropriate on the JDeveloper forum since it is not directly related to JHeadstart itself.
    Hope this helps,
    Evert-Jan de Bruin

  • Can we make a Applet -- Javascript to Managed Bean call Multiple times and vice a versa using a loop?

    Hi,
         I have a requirement wherein im uploading multiple files using an Applet to ADF. With the file sizes relatively lower this works fine but now we have a request to upload bigger files, so the only option i could find is to send the uploaded file data in smaller chunks from the applet to ADF serverside code. But if i want to keep my previous design wherein i was passing the filedata in an encoded string format from the applet to ADF via javascript, i observed that Applets are not able to call a managed bean more than one time and thus only the data sent in the first chunk is received at the client side.
    Could you please provide me with a direction here?

    Can you help understand why you want to use Applet?  Anyhow, check out,  JUpload project on Sourceforge - JUpload - File Upload Applet - General presentation
    for some lead. Not sure if this would help, but no harm checking.

  • Why a getter method of a managed bean WILL be called multiple times

    Why a getter method of a managed bean WILL be called multiple times during the JSF lifecycle?Why this designed?

    This is by design indeed. Each step in the JSF lifecycle can call a getter to get the required information.

  • Generate PDF using Managed Bean with custom HTTP headers

    Background
    Generate a report in various formats (e.g., PDF, delimited, Excel, HTML, etc.) using JDeveloper 11g Release 2 (11.1.2.3.0) upon clicking an af:commandButton. See also the StackOverflow version of this question:
    http://stackoverflow.com/q/13654625/59087
    Problem
    HTTP headers are being sent twice: once by the framework and once by a bean.
    Source Code
    The source code includes:
    - Button Action
    - Managed Bean
    - Task Flow
    Button Action
    The button action:
    <af:commandButton text="Report" id="submitReport" action="Execute" />
    Managed Bean
    The Managed Bean is fairly complex. The code to `responseComplete` is getting called, however it does not seem to be called sufficiently early to prevent the application framework from writing the HTTP headers.
    HTTP Response Header Override
    * Sets the HTTP headers required to indicate to the browser that the
    * report is to be downloaded (rather than displayed in the current
    * window).
    protected void setDownloadHeaders() {
    HttpServletResponse response = getServletResponse();
    response.setHeader( "Content-Description", getContentDescription() );
    response.setHeader( "Content-Disposition", "attachment, filename="
    + getFilename() );
    response.setHeader( "Content-Type", getContentType() );
    response.setHeader( "Content-Transfer-Encoding",
    getContentTransferEncoding() );
    Issue Response Complete
    The bean indirectly tells the framework that the response is handled (by the bean):
    getFacesContext().responseComplete();
    Bean Run and Configure
    public void run() {
    try {
    Report report = getReport();
    configure(report.getParameters());
    report.run();
    } catch (Exception e) {
    e.printStackTrace();
    private void configure(Parameters p) {
    p.put(ReportImpl.SYSTEM_REPORT_PROTOCOL, "http");
    p.put(ReportImpl.SYSTEM_REPORT_HOST, "localhost");
    p.put(ReportImpl.SYSTEM_REPORT_PORT, "7002");
    p.put(ReportImpl.SYSTEM_REPORT_PATH, "/reports/rwservlet");
    p.put(Parameters.PARAM_REPORT_FORMAT, "pdf");
    p.put("report_cmdkey", getReportName());
    p.put("report_ORACLE_1", getReportDestinationType());
    p.put("report_ORACLE_2", getReportDestinationFormat());
    Task Flow
    The Task Flow calls Execute, which refers to the bean's `run()` method:
    entry -> main -> Execute -> ReportBeanRun
    Where:
    <method-call id="ReportBeanRun">
    <description>Executes a report</description>
    <display-name>Execute Report</display-name>
    <method>#{reportBean.run}</method>
    <outcome>
    <fixed-outcome>success</fixed-outcome>
    </outcome>
    </method-call>
    The bean is assigned to the `request` scope, with a few managed properties:
    <control-flow-rule id="__3">
    <from-activity-id>main</from-activity-id>
    <control-flow-case id="ExecuteReport">
    <from-outcome>Execute</from-outcome>
    <to-activity-id>ReportBeanRun</to-activity-id>
    </control-flow-case>
    </control-flow-rule>
    <managed-bean id="ReportBean">
    <description>Executes a report</description>
    <display-name>ReportBean</display-name>
    <managed-bean-scope>request</managed-bean-scope>
    </managed-bean>
    The `<fixed-outcome>success</fixed-outcome>` strikes me as incorrect -- I don't want the method call to return to another task.
    Restrictions
    The report server receives requests from the web server exclusively. The report server URL cannot be used by browsers to download directly, for security reasons.
    Error Messages
    The error message that is generated:
    Duplicate headers received from server
    Error 349 (net::ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION): Multiple distinct Content-Disposition headers received. This is disallowed to protect against HTTP response splitting attacks.Nevertheless, the report is being generated. Preventing the framework from writing the HTTP headers would resolve this issue.
    Question
    How can you set the HTTP headers in ADF while using a Task Flow to generate a PDF by calling a managed bean?
    Ideas
    Some additional ideas:
    - Override the Page Lifecycle Phase Listener (`ADFPhaseListener` + `PageLifecycle`)
    - Develop a custom Servlet on the web server
    Related Links
    - http://www.oracle.com/technetwork/middleware/bi-publisher/adf-bip-ucm-integration-179699.pdf
    - http://www.slideshare.net/lucbors/reports-no-notes#btnNext
    - http://www.techartifact.com/blogs/2012/03/calling-oracle-report-from-adf-applications.html?goback=%2Egde_4212375_member_102062735
    - http://docs.oracle.com/cd/E29049_01/web.1112/e16182/adf_lifecycle.htm#CIABEJFB
    Thank you!

    The problem was that the HTTP headers were in fact being written twice:
    1. The report server was returning HTTP response headers.
    2. The bean was including its own HTTP response headers (as shown in the question).
    3. The bean was copying the entire contents of the report server response, including the headers, into the output stream.
    Firefox ignored the duplicate header errors, but Google Chrome did not.

  • Problems while defining EJB relations for container managed bean

    I am having a problem while trying to create my relations for my container managed bean.
    My Database schema is:
    Order table
    order_id
    message
    WorkItem table:
    order_id
    item_id
    message
    I have defined my OrderBean to have:
    @LocalMethod()
    @CmrField
    public abstract Collection getCmWorkItemsCmr();
    @LocalMethod()
    public abstract void setCmWorkItemsCmr(Collection workItems);
    I am not sure how to define my relation for my class:
    @Relation(cmrField = "cmWorkItemsCmr", multiplicity = Relation.Multiplicity.MANY, name = "Orders-CmWorkItems")
    An order can have many workitems. I am not sure how to fill in the rest for foreign Key jointable and such.
    Any help pointing me in the right direction would be helpful.
    Thanks,
    Ian

    I am having a problem while trying to create my relations for my container managed bean.
    My Database schema is:
    Order table
    order_id
    message
    WorkItem table:
    order_id
    item_id
    message
    I have defined my OrderBean to have:
    @LocalMethod()
    @CmrField
    public abstract Collection getCmWorkItemsCmr();
    @LocalMethod()
    public abstract void setCmWorkItemsCmr(Collection workItems);
    I am not sure how to define my relation for my class:
    @Relation(cmrField = "cmWorkItemsCmr", multiplicity = Relation.Multiplicity.MANY, name = "Orders-CmWorkItems")
    An order can have many workitems. I am not sure how to fill in the rest for foreign Key jointable and such.
    Any help pointing me in the right direction would be helpful.
    Thanks,
    Ian

  • RichTree is not rendered properly when created in Managed Bean

    HI,
    I am trying to create af:tree in managed bean using RichTree. It is not rendering the tree nodes properly. It is only showing the nodes, node text is missing. I am using EL expression to show the value in node element. But when I am creating the af:tree in jspx page, it is working properly.
    Following is the code,
    JSPX Page ------------------------------------------------------------>
    <?xml version='1.0' encoding='windows-1252'?>
    <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.0"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:af="http://xmlns.oracle.com/adf/faces/rich">
    <jsp:directive.page contentType="text/html;charset=windows-1252"/>
    <f:view>
    <af:document id="document1" title="Tree Test">
    <af:form id="form1">
    <af:panelGroupLayout layout="horizontal">
    <af:spacer width="50" height="50"/>
    <af:panelGroupLayout layout="vertical">
    <h1>RCF Tree Component Test</h1>
    <af:spacer height="10" width="10"/>
    <h3>ADF Tree in JSPX</h3>
    <af:spacer height="5" width="10"/>
    <af:tree binding="#{treeTest.tree}" var="node" value="#{treeTest.treeModel}" rowSelection="multiple" rowDisclosureListener="#{treeTest.toggle}" selectionListener="#{treeTest.TableSelect}" inlineStyle="border:1px solid black;">
    <f:facet name="nodeStamp">
    <af:panelGroupLayout>
    <af:image source="#{node.icon}" inlineStyle="margin-right:3px; vertical-align:middle; height:14px; width:16px;"/>
    <af:outputText value="#{node.description}"/>
    </af:panelGroupLayout>
    </f:facet>
    </af:tree>
    </af:panelGroupLayout>
    <af:panelGroupLayout layout="vertical">
    <af:spacer height="65" width="10"/>
    <h3>ADF Tree in UI Bean</h3>
    <af:spacer height="5" width="10"/>
    <af:tree binding="#{treeTest.treeInBean}" inlineStyle="border:1px solid black;"/>
    </af:panelGroupLayout>
    </af:panelGroupLayout>
    </af:form>
    </af:document>
    </f:view>
    <!--oracle-jdev-comment:auto-binding-backing-bean-name:treeTest-->
    </jsp:root>
    Managed Bean ------------------------------------------------------------>
    import java.io.File;
    import java.util.ArrayList;
    import java.util.List;
    import javax.el.ExpressionFactory;
    import javax.el.ValueExpression;
    import javax.faces.context.FacesContext;
    import oracle.adf.view.rich.component.rich.data.RichTree;
    import oracle.adf.view.rich.component.rich.layout.RichPanelGroupLayout;
    import oracle.adf.view.rich.component.rich.output.RichImage;
    import oracle.adf.view.rich.component.rich.output.RichOutputText;
    import org.apache.myfaces.trinidad.event.RowDisclosureEvent;
    import org.apache.myfaces.trinidad.event.SelectionEvent;
    import org.apache.myfaces.trinidad.model.ChildPropertyTreeModel;
    import org.apache.myfaces.trinidad.model.TreeModel;
    public class TreeTest {
    private RichTree tree = new RichTree();
    private TreeModel treeModel;
    final public static String ROOT_DIR = ".";
    private RichTree treeInBean = new RichTree();
    public TreeTest() {
    List nodes = new ArrayList();
    FileNode rootNode = buildFileTree(ROOT_DIR);
    nodes.add(rootNode);
    treeModel = new ChildPropertyTreeModel(nodes, "children") ;
    private void createTreeInBean(List rootNode){
    ChildPropertyTreeModel l_model = new ChildPropertyTreeModel();
    l_model.setChildProperty("children");
    l_model.setWrappedData(rootNode );
    treeInBean.setValue( l_model);
    treeInBean.setRowSelection("multiple");
    treeInBean.setVar( "node" );
    RichOutputText comp = new RichOutputText();
    FacesContext l_context = FacesContext.getCurrentInstance();
    ExpressionFactory l_factory = l_context.getApplication().getExpressionFactory();
    ValueExpression l_expression = l_factory.createValueExpression( FacesContext.getCurrentInstance().getELContext(),
    "#{node.description}", String.class );
    comp.setValueExpression( "value", l_expression );
    RichImage img = new RichImage();
    img.setInlineStyle("margin-right:3px; vertical-align:middle; height:14px; width:16px;");
    ValueExpression l_expressionImg = l_factory.createValueExpression( FacesContext.getCurrentInstance().getELContext(),
    "#{node.icon}", String.class );
    //img.setValueExpression( "source", l_expressionImg );
    img.setSource("images/img1.png");
    RichPanelGroupLayout layout = new RichPanelGroupLayout();
    //layout.getChildren().add( img);
    //layout.getChildren().add( comp);
    //treeInBean.getChildren().add( layout);
    treeInBean.setNodeStamp( layout);
    treeInBean.getNodeStamp().getChildren().add( img );
    treeInBean.getNodeStamp().getChildren().add( comp );
    private static FileNode buildFileTree(String dirpath) {
    File root = new File(dirpath);
    return visitAllDirsAndFiles(root);
    private static FileNode visitAllDirsAndFiles(File dir) {
    FileNode parentNode = process(dir);
    if (dir.isDirectory()) {
    String[] children = dir.list();
    for (int i = 0; i < children.length; i++) {
    FileNode childNode = visitAllDirsAndFiles(new File(dir, children));
    parentNode.getChildren().add(childNode);
    return parentNode;
    public static FileNode process(File dir) {
    FileNode node = new FileNode(dir);
    return node;
    public void TableSelect(SelectionEvent p_event) {
    System.out.println(" Selection Event = " + p_event);
    RichTree l_tree = (RichTree)p_event.getSource();
    System.out.println("Display Row = " + l_tree.getSelectedRowKeys());
    TreeModel model = ((ChildPropertyTreeModel)l_tree.getValue());
    for (Object key : l_tree.getSelectedRowKeys()) {
    model.setRowKey(key);
    System.out.println("Model Data = " + ((FileNode)model.getRowData()));
    public void toggle(RowDisclosureEvent p_rowDisclosureEvent) {
    System.out.println(" Dislosure Event = " + p_rowDisclosureEvent);
    public void setTree(RichTree tree) {
              this.tree = tree;
    public RichTree getTree() {
    return tree;
    public void setTreeModel(TreeModel treeModel) {
    this.treeModel = treeModel;
    public TreeModel getTreeModel() {
    return treeModel;
    public void setTreeInBean(RichTree treeInBean) {
    this.treeInBean = treeInBean;
    public RichTree getTreeInBean() {
    List nodes = new ArrayList();
    FileNode rootNode = buildFileTree(ROOT_DIR);
    nodes.add(rootNode);
    createTreeInBean(nodes);
    return treeInBean;
    File Node Class-------------------------------------------------------------
    import java.io.File;
    import java.util.ArrayList;
    import java.util.Collection;
    public class FileNode {
    private Collection children;
    private boolean nodeSelected;
    private File file;
    public FileNode(File file) {
    this.file = file;
    children = new ArrayList();
    public boolean isDir() {
    return file.isDirectory();
    public boolean isFile() {
    return file.isFile();
    public String getDescription() {
    return file.getName();
    public Collection getChildren() {
    return children;
    public String getIcon(){
    if(children.size() == 0){
    return "images/img1.png";
    } else {
    return "images/img3.png";
    public int getChildCount() {
    if (children == null)
    return 0;
    else
              return children.size();
    public void setNodeSelected(boolean nodeSelected) {
    this.nodeSelected = nodeSelected;
    public boolean isNodeSelected() {
    return nodeSelected;
    public void setFile(File file) {
    this.file = file;
    public File getFile() {
    return file;
    @Override
    public String toString() {
    return getDescription();
    With Regards,
    Sujay

    HI,
    When you see the output of the code, you will find 2 different trees one with proper label and another with out labels. This tree is showing the folder structor. When i am creating the tree in managed bean, the EL expression of the component added in nodeStamp is not getting evaluated. To make sure that same component is stamped as nodeStamp, i tried by setting default value in that component, and it is showing the same hard coded value.
    But the same EL expression is getting evaluated for the tree in JSPX page.
    Sujay

  • How to pass a value from jspx page to the managed bean

    hi,
    i have created a jspx page and manages bean with page flow scope..
    in my jspx page i am searching a employee record from the data base . and getting entire employee details including 'status' as a search result.
    here i want to pass the value of 'status ' field to the managed bean variable called 'stval'.
    can anybody suggest any solution?.......

    As per the details provided in the post above, when the user clicks on the search in the af:query, the results are populated in the table. And you are interested in getting the value of particular column. This could be done by having the custom row selection listener to get the value of the current row (selected row in the table).
    1) Have a custom selection listener:
    <af:table value="#{bindings.EmpDeptVO.collectionModel}" var="row"
    rows="#{bindings.EmpDeptVO.rangeSize}"
    emptyText="#{bindings.EmpDeptVO.viewable ? 'No data to display.' : 'Access Denied.'}"
    fetchSize="#{bindings.EmpDeptVO.rangeSize}"
    rowBandingInterval="0"
    rowSelection="single" id="t1"
    partialTriggers=":::qryId1 ::ctb1 ::commandToolbarButton1"
    columnStretching="column:c1"
    styleClass="AFStretchWidth" columnSelection="multiple"
    first="0" contentDelivery="immediate" autoHeightRows="10"
    binding="#{pageFlowScope.ExampleBean.searchResultsTable}"
    *selectionListener="#{pageFlowScope.ExampleBean.rowSelected}">*
    2) In the method, set the current row programmatically:
    ADFUtil.invokeEL("#{bindings.EmpDeptVO.collectionModel.makeCurrent}",
    new Class[] { SelectionEvent.class },
    new Object[] { selectionEvent });
    3) Get the current row and get the required attribute values and set it in any of the variables in the managed bean:
    Row selectedRow =
    (Row)ADFUtil.evaluateEL("#{bindings.EmpDeptVOIterator.currentRow}");
    String status = selectedRow.getAttribute("Status");
    Thanks,
    Navaneeth

  • Validation, Task Flow, Servlet, Pop-up, and a Managed Bean

    Hi,
    We're trying to display a PDF in a pop-up by calling a Servlet within a JSF page by using a task flow in JDeveloper 11g R2.
    The relevant JSF snippet:
    <af:inlineFrame id="if1" shortDesc="Report" source="/pdfservlet" styleClass="AFStretchWidth"></af:inlineFrame>The /pdfservlet points to a Servlet with a doGet method as follows:
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      response.reset();
      OutputStream out = response.getOutputStream();
      FacesContext context = this.getFacesContext(request, response);
      OracleReportBean bean =
        context.getApplication().evaluateExpressionGet(context, "#{reportBean}", OracleReportBean.class);
      bean.run(context, out);
      removeFacesContext();
      out.close();
    }The Servlet attempts to get the FacesContext, but we've encountered the following exception:
    Caused By: javax.faces.FacesException: Cant instantiate class: oracle.adfinternal.view.faces.component.AdfViewRoot.We removed the following lines from the getFacesContext() method:
    UIViewRoot view = facesContext.getApplication().getViewHandler().createView(facesContext, "");
    facesContext.setViewRoot(view);This avoids the exception above, however... We're trying to get the parameters from the form that was submitted. Here is an example element from the form:
    <h:inputHidden value="MyMedicationList_Report" id="system_REPORT_RESOURCE"/>When the Servlet calls the Managed Bean to retrieve the value, it uses:
    Map<String, String[]> requestParameters = getRequestParameters();
    Parameters p = getParameters();
    for( String key : requestParameters.keySet() ) {
      for( String value : requestParameters.get( key ) ) {
        int i = key.indexOf( ':' );
        if( i >= 0 ) {
          key = key.substring( i + 1 );
        p.put( key, value );
    }Where getRequestParameters() attempts to get the external context to retrieve the request parameter values map:
    return getExternalContext().getRequestParameterValuesMap();The map comes up empty.
    I've tried following http://www.oracle.com/technetwork/developer-tools/adf/learnmore/oct2010-otn-harvest-183714.pdf by setting the web.xml to:
      <!-- JspFilter must be configured before adfBindings. -->
      <filter-mapping>
        <filter-name>JpsFilter</filter-name>
        <servlet-name>PDFServlet</servlet-name>
        <dispatcher>FORWARD</dispatcher>
        <dispatcher>INCLUDE</dispatcher>
        <dispatcher>REQUEST</dispatcher>
      </filter-mapping>
      <filter-mapping>
        <filter-name>adfBindings</filter-name>
        <servlet-name>PDFServlet</servlet-name>
        <dispatcher>FORWARD</dispatcher>
        <dispatcher>REQUEST</dispatcher>
      </filter-mapping>And set the data bindings to:
      <pageMap>
        <page path="/pdfservlet" usageId="ca_bcpra_promis_reporting_view_PDFServletPageDef"/>
      </pageMap>
      <pageDefinitionUsages>
        <page id="ca_bcpra_promis_reporting_view_PDFServletPageDef" path="ca.bcpra.promis.reporting.view.PDFServletPageDef"/>
      </pageDefinitionUsages>The Servlet executes, calls the instantiated managed bean, but cannot read the request parameters.
    The button used to launch the task flow in a dialog is:
    <af:commandButton text="Run Report" id="submitReport" useWindow="true"
                      windowEmbedStyle="inlineDocument" windowModalityType="applicationModal" windowHeight="500"
                      windowWidth="700" action="runReport"/>By using a task flow, the user inputs are validated before the pop-up is opened. We want to keep that behaviour. The PDF opens and then returns with a NullPointerException:
    http://pastebin.com/raw.php?i=PaM64jL4
    The Servlet, through the managed bean, makes a request to the report server to pass parameters and generate a PDF. The PDF is streamed back to the browser via the Servlet.
    What other approaches can we take to:
    1. Send user and system parameters.
    2. Generate a PDF on a remote server.
    3. Stream the PDF back to the user in a pop-up.
    Thank you.

    It is not a static PDF. The PDF is generated, dynamically, on the report server using the parameters from multiple forms on the page.
    We've leveraged the HttpSession getSessionMap() object for now. When combined with a Method Task Flow, we can transfer the data (and FacesContext) to the report Servlet. For example, the following code exposes objects that the Servlet needs through the session:
      public void initReport(String reportName) {
        FacesContext context = FacesContext.getCurrentInstance();
        ExternalContext ec = context.getExternalContext();
        OracleReportBean bean =
          context.getApplication().evaluateExpressionGet(context, "#{reportBean}", OracleReportBean.class);
        bean.setFacesContext(context);
        ec.getSessionMap().put("reportBean", bean);
        ec.getSessionMap().put(Parameters.PARAM_REPORT_RESOURCE, reportName);
      }This means the Servlet can use the object:
      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.reset();
        // Find the bean from the session.
        OracleReportBean bean = (OracleReportBean)request.getSession().getAttribute("reportBean");
        OutputStream out = response.getOutputStream();
        bean.run(out);
        out.close();
      }This allows the bean to generate reports.

  • Manage Bean Scope in Faces Config

    Hi,
    I would like to know if its possible to bind the bean at request level if the bean data involves multiple modifications. Currently I am facing a problem with respect to manage bean scope defination. If i keep the bean scope at request level the bean data is not availabe for modification in next request as a result I need to keep the bean at session level causing heavy loading of session object.
    Can any one advice how to keep bean scope at requesat level and still the data is available for modification.
    Regrds

    Hey ! this is exactly my problem!! :)
    http://forum.java.sun.com/thread.jspa?threadID=611607&tstart=0

  • Accessing property of one managed bean to another in request scope

    Right now my applications managed beans are in session scope.
    I want to change them to request scope .But the problem is how to access the bean methods to another if they are in request scope

    Use RequestMap instead of SessionMap.
    Having multiple and independent managed beans in the request scope for 1 request and the need to access the other bean is somewhat odd design however. You may need to rethink about it. For example, add one of the beans as property of the other bean.

  • Managed Bean Best Practices

    Hi
    Are there any best practices for using Managed Beans?
    We plan to use our own custom-built JSF components. Need to understand how to design backing beans for performance/effort optimization.
    For example :
    1. How to make managed beans thread-safe for concurrent requests, without compromising on efficiency/speed?
    2. How to enforce the J2EE security with managed-beans?
    3. How to decide the scope of these beans to ensure minimal data-storage in session?
    4. How to decide the granularity at which a managed-bean should be used for example :
    4.1 One bean-per-component
    Advantages :
    a) if complex components require special data-holding/processing/event-handling capabilities from bean
    (e.g. datagrid model,tree model,menu model)
    Problems :
    - with multiple components in a page/form
    a) it becomes tedious to debug/change/track which bean serves which component
    b) if session scope is required, too many beans will be cached in session
    c) unnecessarily too many beans will be created on server (= n pages * m components-per-page)
    d) unnecessarily increases the length of faces-config.xml
    4.2 One bean-per-form
    Advantages :
    a) in multi-form web pages, to ensure the functional behaviour of each form is separate/modular in its own bean.
    b) each managed-bean would map to specific/meaningful functionality/user-interaction in use-case.
    Problems :
    - if form includes complex components (datagrid/tree/menu) requiring a specialised bean class, then
    a) either one of the specialized bean has to be augmented with additional logic to handle data/events for all other components within the form
    (Not good, as it mixes-up the responsibilities of component-specific-beans, and the bean may no more be reusable in another form)
    b) or without using component-specific beans, only single form bean should handle the data/events for all components in the form?
    (Neither good, since if a complex tree-compoent is reused in multiple forms, then the logic to handle data/events for such a component will be repeated in those many form-specific managed beans)
    4.3 One bean-per-page
    Advantages :
    a) seems more modular/meaningful way - since a page would map to some feature within the use-case
    b) bean will contain only behaviour which is relevent for the associated page/function within use-case
    Problems :
    a) in multi-form pages, can single bean handle data/events for multiple forms?
    b) if page uses complex component (e.g datagrid, tree) that needs its own bean - how does page-bean exchange data with component-bean?
    Thanks,
    Arti

    Are there any best practices for using Managed
    Beans?There are no best practices for using Managed Beans in terms of Sun, or other vendors recommendations. But there are some patterns that can be applied to the managed beans (The managed bean is already a pattern). Also common sense is allways a good practice.
    For example, the managed bean should not have business logic code, only presentation logic code, etc.
    1. How to make managed beans thread-safe for
    concurrent requests, without compromising on
    efficiency/speed?The beans can be created by request, so concurrency is not an issue. If they are session scope, also is not an issue because, a user can only have one thread running. Only in application scope you must have carefull.
    >
    2. How to enforce the J2EE security with
    managed-beans?see this:
    http://jsf-security.sourceforge.net/
    About jsf-security
    >
    3. How to decide the scope of these beans to ensure
    minimal data-storage in session?If you wnat minimal data-storage in session the answer is request or none.
    In question 4, you make the question and give the answer ;-)

  • Multiple session bean problem

    Hi,
    I am developing an admin module to my web app and have created a 2nd session bean to manage data within the admin component of the site just to keep things cleaner and more logical. However there is a problem which I cannot overcome.
    The source code to my main website is located in soulsurfing package. The source code to my admin website is located in soulsurfing.admin package. Inside this package is the java code to my admin web pages and a 2nd session bean called adminSessionBean. So far so good.
    I dropped a database table into my admin page which created a cachedrowset (CustomerRowSet) in my adminSessionBean and a data provider on my admin page (CustomerDataProvider). Ok things are still going well until now.
    There are two main issues i'm facing.
    1. Setting a breakpoint in my code and trying to step through the code line by line (F10) fails whenever the adminSessionBean appears in the line of code. In actuality the system just hangs until I exit debug mode in which the page finishes loading ok. If I step into the code (F11) it still works ok and if there is no breakpoint at all it loads ok too so there is something wrong with the debugger.
    2. Most importantly there is a problem with either the cachedrowset or the data provider because it simply does not return any data from the database. The sql query works fine in both MySQL and when running from creator too so no problem here. If I put a line of code in to capture the sql statement such as String test_var3 = getAdmin$adminSessionBean().getCustomerRowSet().getStatement().toString() a null exception is thrown. However if I ditch the 2nd session bean (adminSessionBean) and run everything exactly the same through the original session bean (SessionBean1) located in soulsurfing package then it all works fine so there must be conflict somewhere with having multiple session beans perhaps in different packages.
    Can anybody help me?
    Below is the java code to my web page that sets and executes the cachedrowset in the prerender method that is failing. Further below that is the code to my 2nd session bean.
    Thanks.
    customer_list.java
    package soulsurfing.admin;
    import com.sun.rave.web.ui.appbase.AbstractPageBean;
    import com.sun.rave.web.ui.component.Body;
    import com.sun.rave.web.ui.component.Form;
    import com.sun.rave.web.ui.component.Head;
    import com.sun.rave.web.ui.component.Html;
    import com.sun.rave.web.ui.component.Link;
    import com.sun.rave.web.ui.component.Page;
    import javax.faces.FacesException;
    import com.sun.rave.web.ui.component.TextField;
    import com.sun.rave.web.ui.component.Button;
    import com.sun.rave.web.ui.component.PageSeparator;
    import com.sun.rave.web.ui.component.StaticText;
    import com.sun.rave.web.ui.component.Table;
    import com.sun.rave.web.ui.component.TableRowGroup;
    import com.sun.rave.web.ui.component.TableColumn;
    import com.sun.data.provider.impl.CachedRowSetDataProvider;
    import com.sun.rave.web.ui.component.MessageGroup;
    import com.sun.rave.web.ui.model.DefaultTableDataProvider;
    public class customer_list extends AbstractPageBean {
        private int __placeholder;
        private void _init() throws Exception {
            customerDataProvider.setCachedRowSet((javax.sql.rowset.CachedRowSet)getValue("#{adminSessionBean.customerRowSet}"));
        private Page page1 = new Page();
        public Page getPage1() {
            return page1;
        public void setPage1(Page p) {
            this.page1 = p;
        private Html html1 = new Html();
        public Html getHtml1() {
            return html1;
        public void setHtml1(Html h) {
            this.html1 = h;
        private Head head1 = new Head();
        public Head getHead1() {
            return head1;
        public void setHead1(Head h) {
            this.head1 = h;
        private Link link1 = new Link();
        public Link getLink1() {
            return link1;
        public void setLink1(Link l) {
            this.link1 = l;
        private Body body1 = new Body();
        public Body getBody1() {
            return body1;
        public void setBody1(Body b) {
            this.body1 = b;
        private Form form1 = new Form();
        public Form getForm1() {
            return form1;
        public void setForm1(Form f) {
            this.form1 = f;
        private TextField textField1 = new TextField();
        public TextField getTextField1() {
            return textField1;
        public void setTextField1(TextField tf) {
            this.textField1 = tf;
        private TextField textField2 = new TextField();
        public TextField getTextField2() {
            return textField2;
        public void setTextField2(TextField tf) {
            this.textField2 = tf;
        private Button button1 = new Button();
        public Button getButton1() {
            return button1;
        public void setButton1(Button b) {
            this.button1 = b;
        private Button button2 = new Button();
        public Button getButton2() {
            return button2;
        public void setButton2(Button b) {
            this.button2 = b;
        private PageSeparator pageSeparator1 = new PageSeparator();
        public PageSeparator getPageSeparator1() {
            return pageSeparator1;
        public void setPageSeparator1(PageSeparator ps) {
            this.pageSeparator1 = ps;
        private StaticText staticText1 = new StaticText();
        public StaticText getStaticText1() {
            return staticText1;
        public void setStaticText1(StaticText st) {
            this.staticText1 = st;
        private StaticText staticText2 = new StaticText();
        public StaticText getStaticText2() {
            return staticText2;
        public void setStaticText2(StaticText st) {
            this.staticText2 = st;
        private Table table1 = new Table();
        public Table getTable1() {
            return table1;
        public void setTable1(Table t) {
            this.table1 = t;
        private TableRowGroup tableRowGroup1 = new TableRowGroup();
        public TableRowGroup getTableRowGroup1() {
            return tableRowGroup1;
        public void setTableRowGroup1(TableRowGroup trg) {
            this.tableRowGroup1 = trg;
        private MessageGroup messageGroup1 = new MessageGroup();
        public MessageGroup getMessageGroup1() {
            return messageGroup1;
        public void setMessageGroup1(MessageGroup mg) {
            this.messageGroup1 = mg;
        private CachedRowSetDataProvider customerDataProvider = new CachedRowSetDataProvider();
        public CachedRowSetDataProvider getCustomerDataProvider() {
            return customerDataProvider;
        public void setCustomerDataProvider(CachedRowSetDataProvider crsdp) {
            this.customerDataProvider = crsdp;
        private TableColumn tableColumn2 = new TableColumn();
        public TableColumn getTableColumn2() {
            return tableColumn2;
        public void setTableColumn2(TableColumn tc) {
            this.tableColumn2 = tc;
        private StaticText staticText4 = new StaticText();
        public StaticText getStaticText4() {
            return staticText4;
        public void setStaticText4(StaticText st) {
            this.staticText4 = st;
        private TableColumn tableColumn3 = new TableColumn();
        public TableColumn getTableColumn3() {
            return tableColumn3;
        public void setTableColumn3(TableColumn tc) {
            this.tableColumn3 = tc;
        private StaticText staticText5 = new StaticText();
        public StaticText getStaticText5() {
            return staticText5;
        public void setStaticText5(StaticText st) {
            this.staticText5 = st;
        private TableColumn tableColumn11 = new TableColumn();
        public TableColumn getTableColumn11() {
            return tableColumn11;
        public void setTableColumn11(TableColumn tc) {
            this.tableColumn11 = tc;
        private StaticText staticText13 = new StaticText();
        public StaticText getStaticText13() {
            return staticText13;
        public void setStaticText13(StaticText st) {
            this.staticText13 = st;
        public customer_list() {
        protected adminSessionBean getAdmin$adminSessionBean() {
            return (adminSessionBean)getBean("admin$adminSessionBean");
        protected soulsurfing.ApplicationBean1 getApplicationBean1() {
            return (soulsurfing.ApplicationBean1)getBean("ApplicationBean1");
        protected soulsurfing.SessionBean1 getSessionBean1() {
            return (soulsurfing.SessionBean1)getBean("SessionBean1");
        protected soulsurfing.RequestBean1 getRequestBean1() {
            return (soulsurfing.RequestBean1)getBean("RequestBean1");
        public void init() {
            super.init();
            try {
                _init();
            } catch (Exception e) {
                log("customer_list Initialization Failure", e);
                throw e instanceof FacesException ? (FacesException) e: new FacesException(e);
        public void preprocess() {
        public void prerender() {
            try {
                if (getAdmin$adminSessionBean().getFilter1().equalsIgnoreCase("")) {
                    getAdmin$adminSessionBean().getCustomerRowSet().setString(1, "%");
                } else {
                    getAdmin$adminSessionBean().getCustomerRowSet().setString(1, getAdmin$adminSessionBean().getFilter1());
                if (getAdmin$adminSessionBean().getFilter1().equalsIgnoreCase("")) {
                    getAdmin$adminSessionBean().getCustomerRowSet().setString(2, "%");
                } else {
                    getAdmin$adminSessionBean().getCustomerRowSet().setString(2, getAdmin$adminSessionBean().getFilter2());
                getAdmin$adminSessionBean().getCustomerRowSet().execute();
                customerDataProvider.refresh();
                customerDataProvider.cursorFirst();
                getAdmin$adminSessionBean().setRowCount(customerDataProvider.getRowCount());
                getAdmin$adminSessionBean().setMsg(getAdmin$adminSessionBean().getRowCount() + " records returned.");
                //i have a breakpoint here which hangs when stepping over code however works if breakppoint not set
                String test_var1 = getAdmin$adminSessionBean().getFilter1();
                int test_var2 = getAdmin$adminSessionBean().getRowCount();
            } catch (Exception e) {
                log("Exception occurred!!", e);
                error("Error: "+e.getMessage()); //null exception is being caught
        public void destroy() {
            customerDataProvider.close();
    adminSessionBean.java
    package soulsurfing.admin;
    import com.sun.rave.web.ui.appbase.AbstractSessionBean;
    import javax.faces.FacesException;
    import com.sun.sql.rowset.CachedRowSetXImpl;
    public class adminSessionBean extends AbstractSessionBean {
        private int __placeholder;
        private void _init() throws Exception {
            customerRowSet.setDataSourceName("java:comp/env/jdbc/SoulSurfing_User");
            customerRowSet.setCommand("SELECT * \nFROM customer ");
            customerRowSet.setTableName("customer");
        private CachedRowSetXImpl customerRowSet = new CachedRowSetXImpl();
        public CachedRowSetXImpl getCustomerRowSet() {
            return customerRowSet;
        public void setCustomerRowSet(CachedRowSetXImpl crsxi) {
            this.customerRowSet = crsxi;
        public adminSessionBean() {
        protected soulsurfing.ApplicationBean1 getApplicationBean1() {
            return (soulsurfing.ApplicationBean1)getBean("ApplicationBean1");
        public void init() {
            super.init();
            try {
                _init();
            } catch (Exception e) {
                log("adminSessionBean Initialization Failure", e);
                throw e instanceof FacesException ? (FacesException) e: new FacesException(e);
        public void passivate() {
        public void activate() {
        public void destroy() {
        private String filter1 = "";
        public String getFilter1() {
            return this.filter1;
        public void setFilter1(String filter1) {
            this.filter1 = filter1;
        private String filter2 = "";
        public String getFilter2() {
            return this.filter2;
        public void setFilter2(String filter2) {
            this.filter2 = filter2;
        private int rowCount;
        public int getRowCount() {
            return this.rowCount;
        public void setRowCount(int rowCount) {
            this.rowCount = rowCount;
        private String msg;
        public String getMsg() {
            return this.msg;
        public void setMsg(String msg) {
            this.msg = msg;
    }

    Hi Harini,
    What I didn't explain in my initial post is that there are more than 2 views in my application.  There are a total of 9 jsp's so far, so I coded multiple controllers due to the high amount of views.  After taking the HTMLB training class, I noticed that the examples used contained no more than 2 jsp's, so only 1 controller was needed.
    However, I talked with another Portal developer, and he suggested that it would be simpler to code the application using only 1 controller.  The problem is, I will have 1 LOOOOONG controller since there are many buttons across all of the jsp's (hence many events that will need to be handled) and many beans that need to be populated.
    Harini, thanks very much for offering to view my par file.  I think I have solved the problem on my own, but could you let me know what the design standard is for an application of this size?  Think of an online banking application that needs to handle bill payment (paying the bill, viewing past payments, etc.,).
    Would you use 1 controller for this type of application?
    Thanks very much for your help.
    -Jamie

  • Managed beans scalability

    Hi guys,
    It seems to be a standard practice for each JSP to have a corresponding backing bean. This seems to work fairly well for a relatively small Web applications.
    Web applications that we deploy sometimes consist of thousands JSPs (as high as 10 thousand and even more). Even though managed beans are created lazily, just loading them into a JVM takes up a fair amount of memory. We've discovered in the past that web containers do not have the tendency of unloading classes once all class instances are destroyed. Therefore, a large number of backing bean classes in itself may present a problem.
    We delt with this issue in the pre-JSF implementaiton of our Web application quite effectively. However, our model beans needed an ID of the HTML component when they were retrieving its value.
    I wonder if any thought has been given to such scalability issues?
    I do not believe that using single backing bean for multiple JSPs really solves the problem either. It will make development of the application quite messy...
    Any help, thoughts, ideas would be greatly appreciated.
    Vadim.

    I am wondering whether my question below is simply silly, or nobody really had to deal with these kinds of issues?
    Thanks in advance,
    Vadim.

  • Dynamic Declarative Component managed bean returned null

    Hi,
    In a project from an application a DDC component is defined. This component uses a managed/backing bean with view scope.
    Using this component inside this project is working fine. This component should be used in other view controller projects, and here where the problems are.
    This project(let's call it Common) is deployed as ADF Library jar, and used in the other V-C projects.
    The big problem is that the managed bean defined for the logic of this component is not 'reacheable'.
    (Another problem is that the attribute value is not seen as its EL expression but as string, for this i found a workaround.)
    In project Common the adfc-config.xml file:
    <adfc-config xmlns="http://xmlns.oracle.com/adf/controller" version="1.2">
      <managed-bean id="__4">
        <managed-bean-name id="__2">ExtendedShuttle</managed-bean-name>
        <managed-bean-class id="__1">com.xyz.portal.taskflow.common.extendedshuttle.ExtendedShuttle</managed-bean-class>
        <managed-bean-scope id="__3">view</managed-bean-scope>
      </managed-bean>
    </adfc-config>A part from component declaration:
          <af:table var="row" rowBandingInterval="0" id="ta"
                                  rowSelection="multiple" columnStretching="last"
                                  disableColumnReordering="true" fetchSize="-1"
                                  binding="#{viewScope.ExtendedShuttle.allItemsTable}"
                                  value="#{viewScope.ExtendedShuttle.allModel}"
                                  partialTriggers="::dc_cb5 ::dc_cb3"
                                  filterVisible="true"/>The root exception is :
    javax.el.PropertyNotFoundException: Target Unreachable, 'ExtendedShuttle' returned null
    This exception is throw on com.sun.faces.application.ApplicationImpl.createComponent when *#{viewScope.ExtendedShuttle.allItemsTable}* is evaluated.
    Caused By: javax.faces.FacesException: javax.el.PropertyNotFoundException: Target Unreachable, 'ExtendedShuttle' returned null
         at com.sun.faces.application.ApplicationImpl.createComponent(ApplicationImpl.java:262)
         at javax.faces.webapp.UIComponentELTag.createComponent(UIComponentELTag.java:222)
         at javax.faces.webapp.UIComponentClassicTagBase.createFacet(UIComponentClassicTagBase.java:510)
         at javax.faces.webapp.UIComponentClassicTagBase.findComponent(UIComponentClassicTagBase.java:661)
         at javax.faces.webapp.UIComponentClassicTagBase.doStartTag(UIComponentClassicTagBase.java:1142)
         at org.apache.myfaces.trinidad.webapp.UIXComponentELTag.doStartTag(UIXComponentELTag.java:70)
         at oracle.adfinternal.view.faces.taglib.UIXTableTag.doStartTag(UIXTableTag.java:41)
         at oracle.adfinternal.view.faces.unified.taglib.data.UnifiedTableTag.doStartTag(UnifiedTableTag.java:50)
         at oracle.jsp.runtime.tree.OracleJspBodyTagNode.executeHandler(OracleJspBodyTagNode.java:50)
    Caused By: javax.faces.FacesException: javax.el.PropertyNotFoundException: Target Unreachable, 'ExtendedShuttle' returned null
         at com.sun.faces.application.ApplicationImpl.createComponent(ApplicationImpl.java:262)
         at javax.faces.webapp.UIComponentELTag.createComponent(UIComponentELTag.java:222)
         at javax.faces.webapp.UIComponentClassicTagBase.createFacet(UIComponentClassicTagBase.java:510)
         at javax.faces.webapp.UIComponentClassicTagBase.findComponent(UIComponentClassicTagBase.java:661)
         at javax.faces.webapp.UIComponentClassicTagBase.doStartTag(UIComponentClassicTagBase.java:1142)
         at org.apache.myfaces.trinidad.webapp.UIXComponentELTag.doStartTag(UIXComponentELTag.java:70)
         at oracle.adfinternal.view.faces.taglib.UIXTableTag.doStartTag(UIXTableTag.java:41)
         at oracle.adfinternal.view.faces.unified.taglib.data.UnifiedTableTag.doStartTag(UnifiedTableTag.java:50)
         at oracle.jsp.runtime.tree.OracleJspBodyTagNode.executeHandler(OracleJspBodyTagNode.java:50)
    Caused by: javax.el.PropertyNotFoundException: Target Unreachable, 'ExtendedShuttle' returned null
         at com.sun.el.parser.AstValue.getTarget(AstValue.java:88)
         at com.sun.el.parser.AstValue.setValue(AstValue.java:133)
         at com.sun.el.ValueExpressionImpl.setValue(ValueExpressionImpl.java:255)
         at com.sun.faces.application.ApplicationImpl.createComponent(ApplicationImpl.java:259)
    Can you help figure it out, why is not working or why the managed bean is not visible in other projects but only in the one where the component is defined?
    Thank you for your time,
    Bogdan
    ps: how can i format the source code, on this fourm?

    Hi Frank,
    Thank you for the answer.
    I must say i'm quite new with ADF technology and maybe my questions are silly.
    Here is a Quote from "Oracle Fusion Developer Guide - Building Rich Internet Application with Oracle ADF" by Frank Nimphius and Lynn Munsinger Chapter 15 page 498:
    "You build dynamic declarative components *instead* of tag library based declarative components, if component resuse is required *only within the application* that has the component defined."
    Maybe i misunderstand the meaning of application from this sentence, but i need this component in several ViewController projects from only one application (ADF application).
    Tag lib declarative component I would not like to have, since the (automtically) build process is not my responsability and it will take some time till is pinpointed, but still is a last resort.
    Anyway two things are strange:
    1. Why the component is still available in other projects(and the beans not)?
    2. Why when a binding variable (for example: of type FaceCtrlHierBinding) has the correct type in the declarative project and in the order projects is of type String and its value is the variable name?
    Example:
    <af:declarativeComponent ...
    AllItems="#{bindings.Action}"
    In project where the component is declared its value is an instance of FacesCtrlHierBinding and in the rest of the projects is of type String with value "Action".
    Once again thank you a lot,
    Bogdan

Maybe you are looking for

  • Fiefox sinc will not allow entry of the other computers' codes how do I cancel one account? cancel

    Have tried to set up sync between two of my pcs. Both PCs' firefox browsers require the entry of that browsers respective four character, x 3 codes into the OTHER pc for syncing. How do I cancel one of the accounts?

  • How to find RETRO in a given period

    Dear freinds,              Iam doing a payroll report relating to bonus,i would like to check in my coding the retro caculation , iam not sure how we should check the retro calcuation . IF any function module is there where we can check after reading

  • Call+sms filter on wp 8.1?

    A question for folks running Cyan or WP 8.1. I rely heavily on the call+SMS filter. Is this option still present in the 8.1 upgrade? We just got the new HTC One with WP 8.1 and found there is no call block option. Before we go trade for an Icon I nee

  • Settings of Mail Host and Mail Port in transaction: SCOT for the node: SMTP

    Hi, Could anyone please explain me the significance of Mail Host and Mail Port for the SMTP node in transaction: SCOT. It says Mail Server to which outbound mails can be passed. Can i specify my GMAIL ID in the field Mail Host and left blank the Mail

  • Crystal Reports 10 Datasource Location and SQL Query update

    I am running Crystal Reports 10 accessing SQL Server 2008 database on Windows 7. Our product changed database names and I'm trying to update reports to point to the new database. Sounds nice and simple. The database has no structure changes yet, it's