Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple action listeners with a single command component in JSF

Tags:

jsf

jsf-2

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?

like image 551
Tiny Avatar asked Jul 17 '14 14:07

Tiny


1 Answers

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:

  • Call multiple backing bean methods at the same time
  • Differences between action and actionListener
like image 153
Xtreme Biker Avatar answered Jan 03 '23 19:01

Xtreme Biker