JSF中的条件呈现

san*_*dra 11 jsf rendering page-refresh jsf-2

您好我有这个代码有条件地在我的页面中呈现组件:

<h:commandButton action="#{Bean.method()}"  value="Submit">
   <f:ajax execute="something" render="one two" />
</h:commandButton>

<p><h:outputFormat rendered="#{Bean.answer=='one'}" id="one" value="#{messages.one}"/></p>
<p><h:outputFormat rendered="#{Bean.answer=='two'}" id="two" value="#{messages.two}"/></p>
Run Code Online (Sandbox Code Playgroud)

它得到答案并呈现组件,但为了在我的页面上看到它,我需要刷新页面.我该如何解决这个问题?有什么建议?

Bal*_*usC 16

JSF组件的rendered属性是服务器端设置,它控制JSF是否应该生成所需的HTML.

<f:ajax>标签的render属性应指向哪个JavaScript可以抓住由JSF生成的HTML元素的(相对)的客户端ID document.getElementById()从HTML DOM树,以取代上完整的AJAX请求其内容.

但是,由于您要指定从未由JSF呈现的HTML元素的客户端ID(由于rendered存在false),因此JavaScript无法在HTML DOM树中找到它.

您需要将其包装在始终呈现的容器组件中,从而始终在HTML DOM树中可用.

<h:commandButton action="#{Bean.method()}"  value="Submit">
   <f:ajax execute="something" render="messages" />
</h:commandButton>

<p>
    <h:panelGroup id="messages">
        <h:outputFormat rendered="#{Bean.answer=='one'}" value="#{messages.one}"/>
        <h:outputFormat rendered="#{Bean.answer=='two'}" value="#{messages.two}"/>
    </h:panelGroup>
</p>
Run Code Online (Sandbox Code Playgroud)

具体问题无关,你可能存在设计错误.为什么不只是创建一个#{Bean.message}在action方法中使用所需消息设置的属性,以便您可以使用:

<h:commandButton action="#{Bean.method()}"  value="Submit">
   <f:ajax execute="something" render="message" />
</h:commandButton>

<p>
    <h:outputFormat id="message" value="#{Bean.message}" />
</p>
Run Code Online (Sandbox Code Playgroud)