简体   繁体   English

handleNavigation在PhaseListener中不起作用

[英]handleNavigation not working in PhaseListener

I have a PhaseListener to control the user access to some pages, if the user is not logged he is redirected to loginpage. 我有一个PhaseListener来控制用户对某些页面的访问,如果用户未登录,则将其重定向到loginpage。

The problem is that my method handleNavigation is not redirecting the user. 问题是我的方法handleNavigation没有重定向用户。 It runs but does not redirect the user. 它运行但不重定向用户。

When the user types a url that should not have access, the method runs but he page opens without redirected to the login page. 当用户键入不应具有访问权限的URL时,该方法将运行,但是该页面将打开,而不会重定向到登录页面。

What is wrong? 怎么了?

public class AuthorizationListener implements PhaseListener {

  public void afterPhase(PhaseEvent event) {

    FacesContext facesContext = event.getFacesContext();
    String currentPage = facesContext.getViewRoot().getViewId();

    boolean isLoginPage = (currentPage.lastIndexOf("login.xhtml") > -1);
    if(isLoginPage)
      return;

    if(currentPage.indexOf("/rws/") != -1)
    {
      HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(true);
      Object currentUser = session.getAttribute("usuario");

      if (!isLoginPage && currentUser == null) {
        NavigationHandler nh = facesContext.getApplication().getNavigationHandler();
        nh.handleNavigation(facesContext, null, "loginPage");
      }
  } 
}

public void beforePhase(PhaseEvent event) {
    System.out.println("Hellow World");
}

public PhaseId getPhaseId() {
  return PhaseId.RENDER_RESPONSE;
}

}

My faces-config 我的面孔配置

<navigation-rule>
  <from-view-id>/*</from-view-id>
  <navigation-case>
    <from-outcome>loginPage</from-outcome>
    <to-view-id>/login.xhtml</to-view-id>
  </navigation-case>
</navigation-rule>

<lifecycle>
  <phase-listener>br.com.testes.filter.AuthorizationListener</phase-listener>
</lifecycle>

You're executing the code during after phase of render response. 您正在渲染响应的后阶段执行代码。 That's thus after JSF has rendered and completed the response. 因此,在JSF渲染并完成响应之后。 At that moment, the whole HTTP response is already finished and completely sent to the webbrowser. 到那时,整个HTTP响应已经完成,并完全发送到Web浏览器。

This is a point of no return. 这是无可挽回的一点。 Your code is simply being too late in order to change the response. 您的代码太迟了,无法更改响应。

Listen on restore view phase instead. 而是在还原视图阶段进行监听。 Or, better, use a servlet filter . 或者,最好使用servlet过滤器 A JSF phase listener is an overly clumsy tool for the job (it does not kick in on non-JSF requests and is triggered up to 12 times during a JSF request). JSF阶段侦听器是一项过于笨拙的工具(它不会在非JSF请求中启动,并且在JSF请求期间最多触发12次)。 A servlet filter is the right tool for the job. servlet过滤器是完成此任务的正确工具。 You can find a concrete example in this answer: JSF page style missing when using login filter . 您可以在此答案中找到一个具体示例: 使用登录过滤器时缺少JSF页面样式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM