不能将隐藏的commandButton与@RequestScoped支持bean一起使用

时间:2012-02-13 12:08:04

标签: jsf-2

我有以下示例代码。 最初,只有commandButton 两个可见。单击此按钮时,commandButton One 也可见。但是当我点击 One 时,后备bean方法 click1 不会被触发。

以下是我的代码:

XHTML

<h:form id="form1">
    <h:inputHidden id="show" value="#{bean.show1}" />
    <h:commandButton id="button1" value="One" action="#{bean.click1}"
        rendered="#{bean.show1}" />
</h:form>
<h:form id="form2">
    <h:inputHidden id="show" value="#{bean.show1}" />
    <h:commandButton id="button2" value="Two" action="#{bean.click2}" />
</h:form>

支持bean

@RequestScoped
@Named("bean")
public class JsfTrial implements Serializable {

    private static final long serialVersionUID = 2784462583813130092L;

    private boolean show1; // + getter, setter

    public String click1() {
        System.out.println("Click1()");
        return null;
    }

    public String click2() {
        System.out.println("Click2()");
        setShow1(true);
        return null;
    }

}

我找到了BalusC的一个非常翔实的答案。

如果我理解正确,我的问题是由于这个答案的第5点

这是否也意味着我们不能将隐藏的commandButton与 @RequestScoped 支持bean一起使用?

1 个答案:

答案 0 :(得分:6)

您可以使用请求范围,您应该仅通过<f:param>而不是JSF隐藏输入字段<h:inputHidden>将条件作为请求参数传递给后续请求。隐藏输入字段的值仅在“更新模型值”阶段期间在模型中设置,而rendered属性的条件已在“应用请求值”阶段中进行评估。

因此,请使用<f:param>代替<h:inputHidden>

<h:form id="form1">
    <h:commandButton id="button1" value="One" action="#{bean.click1}"
        rendered="#{bean.show1}">
        <f:param name="show1" value="#{bean.show1}" />
    </h:commandButton>
</h:form>
<h:form id="form2">
    <h:commandButton id="button2" value="Two" action="#{bean.click2}">
        <f:param name="show1" value="#{bean.show1}" />
    </h:commandButton>
</h:form>

这样你可以在bean的(post)构造函数中将它们作为请求参数提取出来。

public JsfTrial() {
    String show1 = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("show1");
    this.show1 = (show1 != null) && Boolean.valueOf(show1);
}

丑陋,但CDI没有提供内置注释,而JSF的@ManagedProperty("#{param.show1}")替代。但是你可以homegrow这样的注释。

相关问题