Is it possible to invoke more than one listener method using a single command component? For example,
A view scoped bean:
@ManagedBean
@ViewScoped
public final class ViewScopedBean implements Serializable
{
@ManagedProperty(value = "#{sessionScopedBean}")
private SessionScopedBean sessionScopedBean; //Getter/Setter.
private static final long serialVersionUID = 1L;
public ViewScopedBean() {}
public void action()
{
//Do something.
sessionScopedBean.action();
}
}
A session scoped bean:
@ManagedBean
@SessionScoped
public final class SessionScopedBean implements Serializable
{
private static final long serialVersionUID = 1L;
public SessionScopedBean () {}
public void action() {
//Do something.
}
}
A command button like the one given below,
<h:commandButton value="Action" actionListener="#{viewScopedBean.action}"/>
invokes the method action()
in ViewScopedBean
which in turn invokes the action()
method in SessionScopedBean
by injecting an instance of that bean.
Is it somehow possible do the same on XHTML so that a need to inject a bean just to invoke a method can be eliminated?
Use <f:actionListener binding>
:
<h:commandButton value="Action">
<f:actionListener binding="#{viewScopedBean.action()}"/>
<f:actionListener binding="#{sessionScopedBean.action()}"/>
</h:commandButton />
Note the importance of the parentheses in EL. Omitting them would in this particular example otherwise throw a confusing javax.el.PropertyNotFoundException: Property 'action' not found on type com.example.ViewScopedBean
, because it's by default interpreted as a value expression. Adding parentheses makes it a method expression. See also Why am I able to bind <f:actionListener> to an arbitrary method if it's not supported by JSF?
You could even add an actionListener
and/or an action
method to the component the usual way, which is invoked later on. What it has to be unique is the action
method, which decides the outcome for the processing.
Anyway, keep in mind the listeners are always executed before the action and considered a "warming-up" for it. Your best is to perform the whole logic in the action method, even if you need to do bean injections.
See also:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With