Passing data between managed components in JSF

后端 未结 2 1046
遇见更好的自我
遇见更好的自我 2020-12-09 13:05

Is it actually possible to pass any data between managed components in JSF? If yes, how to achieve this?

Could anyone provide any sample?

相关标签:
2条回答
  • 2020-12-09 13:19

    To add to BalusC's answer, if you are using a dependency-injection framework (spring, guice, etc.), or if using JSF 2.0, you can have one managed bean set into the other using just:

    @Inject
    private Bean2 bean2;
    

    (or the appropriate annotation based on your DI framework)

    0 讨论(0)
  • 2020-12-09 13:26

    There are several ways. If the managed beans are related to each other, cleanest way would be injection. There are different ways depending on JSF version and whether CDI is available.

    CDI

    Just use @Inject.

    @Named
    @SessionScoped
    public class Bean1 {
    
        // ...
    }
    

    @Named
    @RequestScoped
    public class Bean2 {
    
        @Inject
        private Bean1 bean1; // No getter/setter needed.
    }
    

    Other way around can also, the scope doesn't matter because CDI injects under the covers a proxy.

    JSF 2.x

    Use @ManagedProperty.

    @ManagedBean
    @SessionScoped
    public class Bean1 {
    
        // ...
    }
    

    @ManagedBean
    @RequestScoped
    public class Bean2 {
    
        @ManagedProperty("#{bean1}")
        private Bean1 bean1; // Getter/setter required.
    }
    

    Other way around is not possible in this specific example because JSF injects the physical instance and not a proxy instance. You can only inject a bean of the same or broader scope into a bean of a particular scope.

    JSF 1.x

    Use <managed-property> in faces-config.xml.

    public class Bean1 {
    
        // ...
    }
    

    public class Bean2 {
    
        private Bean1 bean1; // Getter/setter required.
    }
    

    <managed-bean>
        <managed-bean-name>bean1</managed-bean-name>
        <managed-bean-class>com.example.Bean1</managed-bean-class>
        <managed-bean-scope>session</managed-bean-scope>
    </managed-bean>
    
    <managed-bean>
        <managed-bean-name>bean2</managed-bean-name>
        <managed-bean-class>com.example.Bean2</managed-bean-class>
        <managed-bean-scope>request</managed-bean-scope>
        <managed-property>
            <property-name>bean1</property-name>
            <value>#{bean1}</value>
        </managed-property>
    </managed-bean>
    

    See also:

    • Backing beans (@ManagedBean) or CDI Beans (@Named)?
    • How to choose the right bean scope?
    • Get JSF managed bean by name in any Servlet related class
    0 讨论(0)
提交回复
热议问题