来自 BalusC 的这个回答 Differences between action and 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>
这是我的 bean
@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...
}
根据 BalusC,actionListener
在这里更适合,但我的示例显示否则。
上面的代码与 action
配合得很好, 但如果我切换到 actionListener
,那么它并不完全有效。使用 actionListener
删除此表的条目需要两次点击 ,而如果我使用 action
,每次单击按钮时它都会删除条目。我想知道是否有任何 JSF 专家可以帮助我理解 action
对比actionListener
注意 如果我切换到 actionListener
, 我的 delete
方法变成public void delete(ActionEvent actionEvent)
最佳答案
你在混淆action
与 actionListener
. actionListener
始终在 action
之前运行.如果有多个 Action 监听器,那么它们将按照注册时的相同顺序运行。这就是为什么当您使用 actionListener
时它无法按预期工作的原因。调用业务操作和 <f:setPropertyActionListener>
设置(准备)将由业务操作使用的属性。这个问题在你之前的问题中被指出并修复了 Is this Primefaces bug or Mojarra/MyFaces bug .
无论你在 delete()
中有什么方法显然是一项业务操作,应由 action
调用反而。业务操作通常会调用 EJB 服务,必要时还会设置最终结果和/或导航到不同的 View 。
关于JSF2 : action and actionListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8683211/