H:从的commandButton第二次点击作品(h:commandButton works fro

2019-10-17 01:52发布

这里是我的代码:

<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不能帮我..我怎样才能使它发挥作用正确? 提前致谢。

Answer 1:

我认为你有这个问题,因为你需要一个重定向(使用的结果,不为空)的主页或注销后的东西。 我有这样的问题,我解决了这样的:

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

希望这可以帮助! :)



Answer 2:

这是因为该窗体的响应URL提交相同生成它的请求。 它提供的网址永远是一个落后你实际上是在那里的影响。

你可以用你的后缀的网址?面孔重定向=真给力JSF重定向你,而不是你转发。

一个更好的概览,说明这里

你的注销操作应该返回一个字符串(),这也是移动到注销功能完成后的页面的名称,但是。



文章来源: h:commandButton works from the second click