我有登录页面的请求范围支持 bean(我正在使用 Spring Security)。当发生身份验证错误时,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 方法中?