这是我的代码:

<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不能帮我。
如何使它正常工作?提前致谢。

最佳答案

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

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


希望这可以帮助! :)

10-01 21:54