Multiple action listeners with a single command component in JSF

旧巷老猫 提交于 2019-12-18 16:48:20

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/24806943/multiple-action-listeners-with-a-single-command-component-in-jsf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!