Transferring Data Between Managed Components in JSF

Is it possible to transfer any data between managed components in JSF? If so, how to do it?

Can someone provide any sample?

+6
java jsf
source share
2 answers

There are several ways. If managed beans are related to each other, the cleanest way would be controlled injection of properties. Suppose Bean1 has the same scope or wider scope than Bean2. First, specify the Bean2 a Bean1 property:

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

Then declare Bean1 in faces-config.xml 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> 

Thus, the bean2 instance has instant access to the bean1 instance.

If you do not want to use managed property injection for some reason, you can also get Application#evaluateExpressionGet() to access it programmatically. Here is an example of extracting Bean1 inside Bean2:

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

However, Bean1 must be declared as a managed bean bean1 in faces-config.xml .

For more information and tips on transferring data inside JSF, you can find this article .

+11
source share

To add BalusC to the answer, if you use a dependency framework (spring, guice, etc.) or use JSF 2.0, you can install one managed bean in another, using only:

 @Inject private Bean2 bean2; 

(or related annotation based on your DI framework)

+4
source share

All Articles