JSF2:action和actionListener

Tha*_*ham 2 jsf action actionlistener primefaces jsf-2

从这个答案由BalusC这里的行动和ActionListener的差异,Use actionListener if you want have a hook before the real business action get executed, e.g. to log it, and/or to set an additional property (by <f:setPropertyActionListener>,.但是,当我决定编写一些代码来测试它时,结果有点不同.这是我的小代码

<h:form id="form"> 
   <h:panelGroup id="mygroup">
     <p:dataTable id="mytable" value="#{viewBean.foodList}" var="item">
         <p:column>
             #{item}
         </p:column>
         <p:column>
             <p:commandButton value="delete" 
                        action="#{viewBean.delete}"
                        update=":form:mygroup">
                 <f:setPropertyActionListener target="#{viewBean.selectedFood}"
                                              value="#{item}"/>
             </p:commandButton>
         </p:column>
      </p:dataTable>
   </h:panelGroup>
</h:form>
Run Code Online (Sandbox Code Playgroud)

这是我的豆子

@ManagedBean
@ViewScoped
public class ViewBean {
    private List<String> foodList;
    private String selectedFood;

    @PostConstruct
    public void init(){

        foodList = new ArrayList<String>();
        foodList.add("Pizza");
        foodList.add("Pasta");
        foodList.add("Hamburger");
    }

    public void delete(){
        foodList.remove(selectedFood);
    }
    //setter, getter...
}
Run Code Online (Sandbox Code Playgroud)

据BalusC,actionListener更适合这里,但我的例子显示,否则.

上面的代码工作得很好action,但如果我切换到actionListener,那它就不太适用了.我需要两次点击才能删除此表的条目actionListener,如果我使用action,则每次单击按钮时都会删除该条目.我想知道是否有任何JSF专家可以帮助我理解actionvsactionListener

注意如果我切换到actionListener,我的delete方法就变成了public void delete(ActionEvent actionEvent)

Bal*_*usC 16

你混淆action使用actionListener.在actionListener之前始终运行action.如果有多个动作侦听器,则它们的运行顺序与它们已注册的顺序相同.这就是当您用于actionListener调用业务操作并<f:setPropertyActionListener>设置(准备)业务操作要使用的属性时,它无法按预期工作的原因.在你之前的问题中指出并修复了这个问题是这个Primefaces错误还是Mojarra/MyFaces错误.

无论你在delete()方法中拥有什么,显然都是一个商业行为,应该由其action来调用.业务操作通常调用EJB服务,并在必要时还设置最终结果和/或导航到不同的视图.