0

我有一个 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。我究竟做错了什么?

这是我的小脸

 <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>
4

1 回答 1

1

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

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

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

    理想情况下,您应该只使用<h:messages/>组件,而无需自己管理消息显示

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

于 2015-06-13T21:49:41.090 回答