tags:

views:

331

answers:

2

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

Could anyone provide any sample?

+5  A: 

There are several ways. If the managed beans are related to each other, cleanest way would be managed property injection. Let assume that Bean1 has the same scope or a broader scope than Bean2. First give Bean2 a Bean1 property:

public class Bean2 {
    private Bean1 bean1; // +getter +setter.
}

Then declare Bean1 in faces-config.xml to be a managed property of Bean2:

<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>

This way the bean2 instance has instant access to the bean1 instance.

If you don't want to use managed property injection for some reasons, then you can also grab Application#evaluateExpressionGet() to access it programmatically. Here's an example of retrieving Bean1 inside Bean2:

FacesContext context = FacesContext.getCurrentInstance();
Bean1 bean1 = (Bean1) context.getApplication().evaluateExpressionGet(context, "#{bean1}", Bean1.class);

The Bean1 must however already be declared as managed bean bean1 in faces-config.xml.

For more info and hints about passing data around inside JSF, you may find this article useful.

BalusC
+1  A: 

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)

Bozho
This works in JSF 2.0 on Java EE 6 as well.
BalusC