h:commandButton从第二次单击开始工作

时间:2012-07-23 18:38:45

标签: java forms jsf jsf-2

这是我的代码:

<h:form>
    <h:messages errorClass="errorMessage" infoClass="infoMessage"
                warnClass="warnMessage"></h:messages>
    <h:panelGroup id="login" layout="block" rendered="#{!securityBean.authorized}">
        <h:outputText value="login:"/>
        <h:inputText id="username" value="#{securityBean.username}"/>
        <h:outputText value="password:"/>
        <h:inputSecret id="password" value="#{securityBean.password}"/>
        <h:commandButton value="login" action="#{securityBean.login}"/>
    </h:panelGroup>

    <h:panelGroup id="logout" layout="block" rendered="#{securityBean.authorized}">
        <h:graphicImage id="img" library="img" name="login_success.jpg"/>
        <h:commandButton value="logout" action="#{securityBean.logout}"/>
    </h:panelGroup>
</h:form>

这是支持bean方法

    public Object login() throws ServletException {
        HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
        try {
            request.login(username, password);
        } catch (ServletException e) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "An Error Occured: Login failed", null));
            e.printStackTrace();
        }
        return null;
    }

    public Object logout(){
        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
        if(session != null){
            session.invalidate();
        }
        return null;
    }
    public boolean isAuthorized() {
        return FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal() != null &&
                FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal().getName() != null &&
                !FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal().getName().isEmpty();
    }

登录后,会出现注销按钮,但仅在第二次点击时有效。正如你所看到的,这里没有使用ajax,所以这个http://balusc.blogspot.com/2011/09/communication-in-jsf-20.html#AjaxRenderingOfContentWhichContainsAnotherForm无法帮助我.. 我怎样才能让它正常工作?提前谢谢。

2 个答案:

答案 0 :(得分:4)

我认为你有这个问题,因为你需要在注销后重定向(使用结果,而不是null)到主页或其他东西。我遇到了这个问题,我解决了这个问题:

public String logout(){
    HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
    if(session != null){
        session.invalidate();
    }
    return "redirectToHomePageAfterLogout";
}

希望这有帮助! :)

答案 1 :(得分:0)

这是因为表单提交的响应URL与生成它的请求相同。它的效果是URL总是落后于你实际所在的位置。

您可以使用?faces-redirect = true为您的网址添加后缀,以强制JSF重定向您而不是转发您。

更好的概述here

你的logOut操作应该返回一个String(),它给出了logOut函数完成后要移动到的页面的名称。

相关问题