Multiple instances of managed bean

后端 未结 2 1455
别那么骄傲
别那么骄傲 2021-01-22 12:40

I\'m using prime-faces Tabs to display multiple input forms. The problem is, there are times when I need to instantiate 2 of the same form. They both of course use the same Mana

相关标签:
2条回答
  • 2021-01-22 12:54

    If you want to use the multiple instance of manager bean, then you can declared it in faces-config.xml file with different names and use its independently. See example

    <managed-bean>
        <managed-bean-name>productSearchForm</managed-bean-name>
        <managed-bean-class>com.company.package.ProductSearchForm</managed-bean-class>
        <managed-bean-scope>session</managed-bean-scope>
    </managed-bean>
    
    <managed-bean>
        <managed-bean-name>productChildFilter</managed-bean-name>
        <managed-bean-class>com.company.package.ProductSearchForm</managed-bean-class>
        <managed-bean-scope>session</managed-bean-scope>
    </managed-bean>
    
    <managed-bean>
        <managed-bean-name>productAttachFilter</managed-bean-name>
        <managed-bean-class>com.company.package.ProductSearchForm</managed-bean-class>
        <managed-bean-scope>session</managed-bean-scope>
    </managed-bean>
    
    0 讨论(0)
  • 2021-01-22 13:05

    Instead of trying to use multiple instances of a managed bean, use ONE managed bean that gives access to multiple instances of a class via e.g. a hashmap or arraylist or whatever you want to use. Just like you would in plain old java programming. You cannot have two variables with the same name:

    @ViewScoped
    @Named
    public class RequestCalculations {
    
        Map<String, RequestCalculation> hm;
    
        @PostConstruct
        public init() {
            hm = new HashMap<>();
            // prepopulate if known upfront
            hm.put("1", new RequestCalculation());
            hm.put("2", new RequestCalculation());
        }
    
        public HashMap<String, RequestCalculation> getCalculations() {
            return hm;
        }
    }
    

    Then use the tabIndex of the tab as the key to the hashmap (or an array list). And in your xhtml do something like

    #{requestCalculations.calculations[myTabIndex]}
    

    You might need to pass this on to the include via a include param if you need this IN the include (as I think you do)

    0 讨论(0)
提交回复
热议问题