使用f:attribute替代f:param来为commandButton添加属性,而不是使用h:commandLink。

7

我希望根据点击的按钮包含具体页面。

如果使用h:commandButton,我无法使用f:param,所以看起来我应该使用f:attribute标记。

对于f:param,我的代码将如下所示:

<h:commandLink action="connectedFilein">
    <f:param name="fileId" value="#{fileRecord.fileId}"/>
<h:commandLink>

<c:if test="#{requestParameters.fileId!=null}">
    <ui:include src="fileOut.xhtml" id="searchOutResults"/>
</c:if>

什么是 f:attribute 案例?
谢谢。
1个回答

15
我假设您正在使用JSF 1.x,否则这个问题就没有意义了。在旧版的JSF 1.x中确实不支持<h:commandButton>中的<f:param>,但自从JSF 2.0起就支持了。 <f:attribute>可以与actionListener结合使用。
<h:commandButton action="connectedFilein" actionListener="#{bean.listener}">
    <f:attribute name="fileId" value="#{fileRecord.fileId}" />
</h:commandButton>

使用

public void listener(ActionEvent event) {
    this.fileId = (Long) event.getComponent().getAttributes().get("fileId");
}

(假设它是Long类型,这是一种经典的ID类型)


更好的方法是使用JSF 1.2中介绍的<f:setPropertyActionListener>标签。

<h:commandButton action="connectedFilein">
    <f:setPropertyActionListener target="#{bean.fileId}" value="#{fileRecord.fileId}" />
</h:commandButton>
或者当您已经运行Servlet 3.0 / EL 2.2兼容的容器(Tomcat 7,Glassfish 3等),并且您的web.xml已声明符合Servlet 3.0时,则可以将其作为方法参数传递。
<h:commandButton action="#{bean.show(fileRecord.fileId)}" />

使用

public String show(Long fileId) {
    this.fileId = fileId;
    return "connectedFilein";
}

与具体问题无关,我强烈建议尽可能使用JSF/Facelets标签而不是JSTL标签。

<ui:fragment rendered="#{bean.fileId != null}">
    <ui:include src="fileOut.xhtml" id="searchOutResults"/>
</ui:fragment>

(在使用JSP而不是Facelets时,<h:panelGroup> 也是可能的并且是最佳方案)


我应该在任何情况下使用bean.property声明吗?请求参数在这里不起作用吗?我想让它更简单。 - sergionni
JSF 2.0支持在<h:commandButton>中使用<f:param>。因此,如果可以的话,请升级它。否则,您当前最好的选择是<f:setPropertyActionListener>。 - BalusC
好的,我知道了。不幸的是,我们在项目中使用的是JSF 1.2。谢谢。 - sergionni

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接