添加来自春豆的 JSF 消息



我在从 Spring 组件向FacesContext添加消息时遇到问题。这是塞纳里奥:

  1. 用户从.xhtml页面登录
  2. 弹簧安全授权用户
  3. 如果用户成功/失败,则从 Spring 托管类(AuthenticationFailureHandlerAuthenticationSuccessHandler(向 UI 返回消息,这是素数。

我无法通过以下方式添加消息:

@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {
private static Logger logger = LoggerFactory.getLogger(LoginFailureHandler.class);
@Override
public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
logger.info("Login failed: " + httpServletRequest.getParameter("j_username"), e);
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Login Error", e.getLocalizedMessage());
FacesContext.getCurrentInstance().addMessage(null, message);
httpServletResponse.sendRedirect("/timsgui/login.jsf?error=1");
}
}

因为此类不在 JSF 生命周期中,所以FacesContext.getCurrentInstance()返回null。这是我的jsf页面:

<body>
<p:growl id="growl" sticky="true" showDetail="true" life="3000" />
<h:form name="login" action="../j_spring_security_check" method="POST">
<h:panelGrid>
<h:outputLabel for="j_username" value="Username:"/>
<p:inputText id="j_username"/>
<h:outputLabel for="j_password" value="Password:"/>
<p:password id="j_password"/>
<!-- need CSRF protection which is enabled default after Spring 4-->
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
<p:commandButton value="Login" update="growl" type="submit"/>
</h:panelGrid>
</h:form>

我试图将FacesContext注入春豆中,但它仍然返回null

@ManagedProperty("#{facesContext}")

无论如何,我可以将当前FacesContext注入春豆或任何其他想法,我可以将春豆的全局信息添加到FacesContext而无需FacesContext.getCurrentInstance().addMessage()

好的,我解决了这个问题。感谢@M.Delinum和@Xtreme Biker的建议。我将消息注入 HttpSession 并从 http 范围获取它。这是最终代码:

@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {
private static Logger logger = LoggerFactory.getLogger(LoginFailureHandler.class);
@Override
public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
logger.info("Login failed: " + httpServletRequest.getParameter("j_username"), e);
HttpSession session = httpServletRequest.getSession(false);
if (session != null) {
session.setAttribute("loginFailMessage", "Login is failed");
}
httpServletResponse.sendRedirect("/timsgui/login.jsf?error=true");
}
}
<h:outputText value="#{sessionScope['loginFailMessage']}" rendered="#{not empty sessionScope['loginFailMessage']}" styleClass="highlight"/>

最新更新