Primefaces ajax根据backbean结果更新不同的面板

RSo*_*ira 3 ajax jsf primefaces

我是JSF,Primefaces和Ajax的新手,所以我要做的是更新一个面板,如果我的后端bean的验证是真的,并且当它是假的时更新另一个面板.

<h:panelGroup id="panel1">
    ...
    <h:commandButton id="btn1" action="#{bean.validate}">
        <p:ajax process="panel1" update="panel1"/>
    </h:commandButton>
</h:panelGroup>

<h:panelGroup id="panel2">
    ...
</h:panelGroup>
Run Code Online (Sandbox Code Playgroud)

后豆:

public void validate() {
    ...
    if(validatecondition) {
        // Update panel 1
    } else {
        // update panel 2
    }
}
Run Code Online (Sandbox Code Playgroud)

那么使用ajax可以做到这一点吗?提前致谢!!

kol*_*sus 8

当然,有两种方式.既然你正在使用primefaces,那么两种选择就更容易了

  1. 使用RequestContext对象有选择地更新面板.您的代码将如下所示:

     public void validate() {
       RequestContext context = RequestContext.getCurrentInstance();
       if(validatecondition) {
         context.update("panel1");
       } else {
         context.update("panel2");
       }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. PartialViewContext只需更多一点打字,JSF 就可以完成同样的工作

    FacesContext ctxt = FacesContext.getCurrentInstance(); //get your hands on the current request context
         if(validatecondition) {
             ctxt.getPartialViewContext().getRenderIds().add("panel1");
           } else {
             ctxt.getPartialViewContext().getRenderIds().add("panel2");
           }
    
    Run Code Online (Sandbox Code Playgroud)

getRenderIds()调用返回一个组件ID列表,JSF将在响应完成时通过ajax更新.这基本上是RequestContext关于素面的内容.