如果我们收到来自提交的错误响应,则提交可能使用 ajax 的 JSF 2 表单的最佳实践

Best Practice for submitting a JSF 2 form that might use ajax if we have an error response from the submit

我有一个提交按钮,可以使用下面的按钮提交到数据库。 如果此按钮 return "error",我想使用 AJAX 删除表单及其内容并添加文本来代替表单。

编辑:

点击提交按钮后停留在同一页面的原因是,提交后在当前页面和重定向页面上使用了表单上下相同的CMS内容。因此,更容易删除表单并显示错误页面。这将避免由于重定向而重新加载整个页面。

</h:form id="myForm">
  ...
  <h:commandButton action="#{testBean.submitForm}"
                   type="submit" value="Create Button">
  </h:commandButton>
</h:form>

记得使用 <h:head><h:body> 而不是 <head><body>

<h:panelGroup id="mypanelgroup">   
    <h:outputText value="#{testBean.errorMessage}" rendered="#{testBean.errorMessage ne null}" />

    <h:form rendered="#{testBean.errorMessage eq null}">
        <!--  -->
        <h:commandButton value="submit" action="#{testBean.submitForm()}">
           <f:ajax execute="@form" render=":mypanelgroup"></f:ajax> 
        </h:commandButton>
    </h:form>
</h:panelGroup>


@ManagedBean
public class TestBean {

    private String errorMessage = null;

    public String getErrorMessage() {
        return errorMessage;
    }

    public void submitForm(){
        // .....
        //if(error){
            this.errorMessage = "My error Message";
        //} 
    }
}

最初,<h:outputText> 未呈现,因为 errorMessage 默认设置为 null