【问题标题】:Clear h:messages after page refreshed页面刷新后清除 h:messages
【发布时间】:2015-09-15 02:16:49
【问题描述】:

我有一个 JSF 登录页面(用于 Spring Security)和一个全局消息,用于显示错误登录用户/密码的消息。

这是我的表格:

<f:event listener="#{loginBean.updateMessages}" type="preRenderView"/>

<h:form prependId="false" >

    <h:outputLabel value="User Name:" for="username"/>
    <h:inputText id="username" required="true" value="#{loginBean.name}"/>
    <h:message id="usernMsg" for="username"/> <br/>

    <h:outputLabel value="Password:" for="password"/>
    <h:inputSecret id="password" value="#{loginBean.password}" required="true"/>
    <h:message id="passMsg" for="password"/><br/>

    <h:messages id="glbMsg" globalOnly="true"/><br/>

    <h:commandButton value="Submit" action="#{loginBean.doLogin}"/>

</h:form>

我用updateMessages()更新消息:

public void updateMessages() {
    Exception ex = (Exception) FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
            .get(WebAttributes.AUTHENTICATION_EXCEPTION);

    if (ex != null) {
        FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.getMessage(), ""));
        setUsername("");
        setPassword("");
    }
}

问题是当用户输入错误的凭据时,会显示消息,但是当用户刷新登录页面(使用F5 或在文本字段为空时单击提交按钮)时,之前的全局消息 (glbMsg) 值不会删除。

我在提交按钮中尝试了ajax render="...",但没有成功。

【问题讨论】:

    标签: jsf spring-security


    【解决方案1】:

    再次回顾问题,现在以正确的方式。您实际上不想清除h:messages。您实际上想清除异常(触发了h:messages)。它只是每次都重新显示,因为不是null每次都出现异常。

    Spring Security 将最后一次身份验证失败存储为 session 中的异常。获取方式一目了然:

    Exception ex = (Exception) FacesContext.getCurrentInstance().getExternalContext()
        .getSessionMap().get(WebAttributes.AUTHENTICATION_EXCEPTION);
    

    除非您使会话无效,或者 Spring Security 自己将其全部删除,否则它会在整个会话中一直存在。由于 Spring Security 显然不会删除它,因此您必须自己动手。

    Exception ex = (Exception) FacesContext.getCurrentInstance().getExternalContext()
        .getSessionMap().remove(WebAttributes.AUTHENTICATION_EXCEPTION);
    

    【讨论】:

      猜你喜欢
      • 2017-06-03
      • 2018-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-24
      • 1970-01-01
      • 1970-01-01
      • 2019-02-11
      相关资源
      最近更新 更多