如何使用jsf,ajax验证帐户而不转移到另一个页面

时间:2013-05-19 07:06:53

标签: ajax jsf facelets

我想登录但不转移到另一页。单击“登录”按钮或链接时,会将用户名和密码的值传递给服务器,然后验证数据库中的帐户。如果此帐户不存在,我希望显示提醒或消息。怎么实现呢?有人告诉我,我应该使用ajax,但是怎么样?感谢。

这是jsf代码示例:

<h:form>
    <h:inputText id="username" required="true"
                 value="#{loginManagedBean.username}" />
    <h:inputSecret id="password" required="true"
                   value="#{loginManagedBean.password}" />
    <h:commandLink type="submit"
                   id="login_button" value="Sign In" />
</h:form>

抱歉,我忘记了。我使用jsf的持续版本。

1 个答案:

答案 0 :(得分:0)

您可以更改视图代码以添加ajax功能:

<h:form id="loginform">
    <h:panelGroup rendered="#{not loginManagedBean.isLogged}">
        <h:inputText id="username" required="true" value="#{loginManagedBean.username}" />
        <h:inputSecret id="password" required="true" value="#{loginManagedBean.password}" />
        <h:commandLink id="login_button" value="Sign In">
            <f:ajax listener="#{loginManagedBean.onButtonLoginClick}" render="loginform" />
        </h:commandLink>
    </h:panelGroup>
    <h:panelGroup rendered="#{loginManagedBean.isLogged}">
        <h:commandLink id="logout_button" value="Sign Out">
            <f:ajax listener="#{loginManagedBean.onButtonLogoutClick}" render="loginform" />
        </h:commandLink>
    </h:panelGroup>
</h:form>

将你的bean改成这样的东西:

@ManagedBean
@RequestScoped
public class LoginManagedBean
{
    private String username;
    private String password;

    public void setUsername(String username)
    {
        this.username = username;
    }

    public String getUsername()
    {
        return this.username;
    }

    public void setPassword(String password)
    {
        this.password = password;
    }

    public String getPassword()
    {
        return this.password;
    }

    public boolean getIsLogged()
    {
        return false;// change to verify in session if logged
    }

    public void onButtonLoginClick(AjaxBehaviorEvent event)
    {
        // Do the login stuff verification, put your user in session, etc
    }

    public void onButtonLogoutClick(AjaxBehaviorEvent event)
    {
        // Do the logout stuff verification, remove your user in session, etc
    }
}

注意:您还可以添加登录错误消息并使用<h:message />显示它们。

更多信息:

using Ajax with Facelets