JSF中具有单个命令组件的多个动作侦听器 [英] Multiple action listeners with a single command component in JSF

查看:94
本文介绍了JSF中具有单个命令组件的多个动作侦听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用单个命令组件调用多个侦听器方法?例如,

Is it possible to invoke more than one listener method using a single command component? For example,

视图范围的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();
    }
}

会话范围的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}"/>

调用ViewScopedBean中的action()方法,该方法又通过注入该bean的实例来调用SessionScopedBean中的action()方法.

invokes the method action() in ViewScopedBean which in turn invokes the action() method in SessionScopedBean by injecting an instance of that bean.

是否有可能在XHTML上做同样的事情,从而消除注入仅用于调用方法的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?

推荐答案

使用

请注意括号在EL中的重要性.在此特定示例中,省略它们会抛出混乱的javax.el.PropertyNotFoundException: Property 'action' not found on type com.example.ViewScopedBean,因为默认情况下会将其解释为值表达式.添加括号使其成为方法表达式.另请参见为什么我可以绑定< f:actionListener>到JSF不支持的任意方法?

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?

您甚至可以按常规方式向组件添加actionListener和/或action方法,稍后再调用.它必须唯一的是action方法,该方法确定处理的结果.

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.

无论如何,请记住,侦听器总是在操作之前执行,并被视为预热".最好的办法是即使您需要进行bean注入,也要在action方法中执行整个逻辑.

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.

另请参见:

  • Call multiple backing bean methods at the same time
  • Differences between action and actionListener

这篇关于JSF中具有单个命令组件的多个动作侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆