JSF中如何将actionListener作为参数传递以复用通用确认对话框代码
实现方案
完全可以通过参数传递actionListener实现代码复用,以下是两种PrimeFaces生态下常用的成熟方案:
方案1:Facelets复合组件(灵活度最高,支持多自定义参数)
你可以将通用确认对话框封装为可复用的复合组件,支持传入自定义的actionListener、提示文本、组件ID等参数:
- 新建复合组件文件
resources/components/confirmDeleteDialog.xhtml,代码如下:
<ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:p="http://primefaces.org/ui" xmlns:cc="http://xmlns.jcp.org/jsf/composite" xmlns:ui="http://xmlns.jcp.org/jsf/facelets"> <!-- 定义可传入的参数,method-signature指定actionListener是无返回值的方法 --> <cc:interface> <cc:attribute name="widgetVar" required="true" /> <cc:attribute name="actionListener" required="true" method-signature="void actionListener()" /> <cc:attribute name="message" default="Deseja apagar o registro selecionado?" /> <cc:attribute name="header" default="Confirmar" /> <cc:attribute name="update" default="@form" /> </cc:interface> <cc:implementation> <p:confirmDialog widgetVar="#{cc.attrs.widgetVar}" showEffect="fade" width="500" message="#{cc.attrs.message}" header="#{cc.attrs.header}" severity="warn"> <p:commandButton value="Sim" icon="pi pi-check" actionListener="#{cc.attrs.actionListener}" process="@this" update="#{cc.attrs.update}" oncomplete="PF('#{cc.attrs.widgetVar}').hide()"/> <p:commandButton value="Não" type="button" styleClass="ui-button-danger" icon="pi pi-times" onclick="PF('#{cc.attrs.widgetVar}').hide()" style="margin-left: 30px" /> </p:confirmDialog> </cc:implementation> </ui:composition>
- 业务页面引入使用,只需要传入对应参数即可:
<!-- 页面头部先引入组件命名空间 --> xmlns:components="http://xmlns.jcp.org/jsf/composite/components" <!-- 页面中调用组件,传入业务对应的actionListener --> <components:confirmDeleteDialog widgetVar="deleteCargoDialog" actionListener="#{cargoController.excluir}" />
方案2:全局确认对话框(代码量最少,适合统一交互规范的场景)
PrimeFaces原生支持全局确认对话框,全工程只需要声明一次对话框,所有页面的确认操作都可以直接复用:
- 在公共模板(比如页面底部、顶部公共引入文件)中添加全局确认对话框,添加
global="true"属性:
<p:confirmDialog widgetVar="globalConfirmDialog" global="true" showEffect="fade" width="500" header="Confirmar" severity="warn"> <p:commandButton value="Sim" icon="pi pi-check" process="@this" update="@form" oncomplete="PF('globalConfirmDialog').hide()"/> <p:commandButton value="Não" type="button" styleClass="ui-button-danger" icon="pi pi-times" onclick="PF('globalConfirmDialog').hide()" style="margin-left: 30px" /> </p:confirmDialog>
- 业务页面的触发按钮不需要单独绑定对话框,只需要内嵌
<p:confirm>标签即可,actionListener直接定义在触发按钮上:
<p:commandButton value="删除选中项" actionListener="#{cargoController.excluir}"> <!-- 可自定义当前操作的提示文本 --> <p:confirm message="Deseja apagar o registro selecionado?" /> </p:commandButton>
内容的提问来源于stack exchange,提问作者Rodrigo Vidal
相关产品推荐
相关产品推荐

