在JSF中添加来自方法的消息

在JSF中添加来自方法的消息,jsf,spring-security,Jsf,Spring Security,我使用SpringSecurity为登录页面提供了请求范围支持bean。当身份验证错误发生时,Spring将其放到上下文中,我正在尝试将错误消息添加到我的页面中 public void doLogin() throws IOException { final FacesContext context = FacesContext.getCurrentInstance(); ExternalContext externalContext = context.getExternalC

我使用SpringSecurity为登录页面提供了请求范围支持bean。当身份验证错误发生时,Spring将其放到上下文中,我正在尝试将错误消息添加到我的页面中

public void doLogin() throws IOException {
    final FacesContext context = FacesContext.getCurrentInstance();
    ExternalContext externalContext = context.getExternalContext();
    externalContext.dispatch("/j_spring_security_check");

    if (externalContext.getRemoteUser() == null) {
        Exception loginError = (Exception) externalContext.getSessionMap().get(
                AbstractProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY);
        if (loginError instanceof BadCredentialsException) {
            externalContext.getSessionMap().put(
                    AbstractProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY, null);
            context.addMessage("loginBtn", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Invalid credentials!", null));
            context.responseComplete();
        }
    }

    context.renderResponse();
}
我的页面:

  <a4j:form prependId="false">
        <h:panelGrid columns="2" cellpadding="5" >
            <h:outputText value="#{msgs.login_username}"/>
            <h:inputText id="j_username"/>

            <h:outputText value="#{msgs.login_password}"/>
            <h:inputSecret id="j_password"/>

            <h:outputText value=" "/>
            <f:facet name="footer">
                <h:panelGroup>
                    <h:commandButton type="submit" id="loginBtn" action="#{guest.doLogin}" value="#{msgs.login}" />
                    <rich:spacer width="5" height="1"/>
                    <rich:message id="errorForLogin" for="loginBtn">
                        <f:facet name="errorMarker">
                            <h:graphicImage value="./resources/forbidden.gif"/>
                        </f:facet>
                    </rich:message>
                </h:panelGroup>
            </f:facet>
        </h:panelGrid>
        <br/><br/>
    </a4j:form>

但这是不可行的。我试图将错误显示代码放入@PostConstruct方法,但这没有帮助。只有当我实现我的PhaseListener时,这才有效,但我认为这是个坏主意,因为它会在每个请求上调用。我的错误是,有一些方法可以从方法中添加错误消息,可能是在@PostConstruct方法中?

您可以从另一个方面进行处理。在使用SpringSecurity时,您可以将AuthenticationProcessingFilter子类化,并重写onUnsuccessfulAuthentication方法。您可以在那里输入所需行为的代码。然后,您只需在对应的bean定义中为Spring安全性指定自定义身份验证处理过滤器类,而不是AuthenticationProcessingFilter