Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

jsf 2 - Multiple action listeners with a single command component in JSF

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...