【问题标题】:JSF ajax render message and redirectJSF ajax 渲染消息和重定向
【发布时间】:2015-06-11 08:35:48
【问题描述】:

我有一个 JSF 应用程序,用户在其中登录一个登录表单并插入他们的电子邮件和密码。 ManagedBean 有以下两种方法。

checkIdentity1() 方法返回一个 URL(如果验证不正确,则返回一个 URL(“”,以便留在同一页面,或者 /useraccount.xhtml,如果插入数据正常,则转到下一页)。

checkIdentity2() 方法返回一个布尔值(如果验证错误,则返回 false,以便显示消息,如果正确,则返回 true)。

loginManagedBean.java

public String checkIdentity1()
{
    String strResponse="";

    //check id

    if(email.equals("jose@a.com") && password.equals("1234"))
    {
        strResponse="/useraccount.xhtml?faces-redirect=true";
    } else {

    }
    //
        return strResponse;
}

public boolean checkIdentity2()
{
    boolean bResponse=false;
    //check id

    if(email.equals("jose@a.com") && password.equals("1234"))
    {
       //setpassIncorrecta(false); 

    } else {
        bResponse=true;
    }

    //

    return bResponse;
}

我想要做的是混合 ajax 和 JSF 以在我单击登录按钮并且验证失败时显示“电子邮件和/或密码不正确”,并在验证正常时转到 account.xhtml。但是,当我插入不正确的电子邮件和密码时,不会显示任何消息,并且当我正确插入它们时,页面不会重定向到 account.xhtml。我做错了什么?

这是我的 Facelet

 <h:form> 
    <!--Email-->
    <h:inputText id="email" label="email" required="true" size="32" maxlength="32"
         value="#{loginManagedBean.email}"
         requiredMessage="Insert your email">              
    </h:inputText>
    <h:message for="email" />


    <!--Password-->
    <h:inputSecret id="password" label="password" required="true" size="32" maxlength="40"
        value="#{loginManagedBean.password}" 
        requiredMessage="Insert your password">            
    </h:inputSecret>
    <h:message for="password" />


    <!--Button-->
    <h:commandButton value="Login" action="#{loginManagedBean.checkIdentity1()}">
    <f:ajax execute="@form" render=":loginErrorMessage" />
    </h:commandButton>

</h:form>


<h:panelGroup id="loginErrorMessage">
    <h:outputText value="Email and/or password incorrect" rendered="#{!loginManagedBean.checkIdentity2()}" />
</h:panelGroup>

【问题讨论】:

  • 如果验证失败,checkIdentity1 将不会被执行,checkIdentity2 也不会返回您期望的结果,这是先前失败的直接结果。
  • 您能解释一下原因吗?还是举个例子?
  • JSF 的底线是,如果请求验证失败,命令按钮上的action 将不会被执行——这是 JSF 的规则。所以你现在的逻辑是行不通的,因为你的请求的处理不会到执行checkIdentity1方法那么远

标签: ajax jsf rendered-attribute


【解决方案1】:

就像我在评论中解释的那样,这就是 JSF 的工作方式:如果请求验证失败,action 方法将不会被执行。这就是JSF request processing lifecycle 的定义(我不会在这里讨论)。出于此答案的目的,您只需要知道请求参数的验证发生在考虑 action 方法之前。话虽如此,如果验证失败,请求处理就会在那里短路。要实现您的目标,您应该考虑以下几点:

  1. 要有条件地呈现该组件,您可以检查页面中的验证状态:

    <h:outputText value="Email and/or password incorrect" rendered="#{facesContext.validationFailed}" />
    

    理想情况下,您应该只使用&lt;h:messages/&gt; 组件,您不需要自己管理消息显示

如果验证失败,JSF 将默认停留在同一页面上,因此您无需为此采取任何特殊步骤

【讨论】:

    猜你喜欢
    • 2013-11-01
    • 1970-01-01
    • 2011-12-12
    • 2012-04-13
    • 1970-01-01
    • 2016-09-05
    • 2012-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多