Navigate to a different page in preRenderViewEvent depending on user permission; ExternalContext#dispatch() does not work

☆樱花仙子☆ 提交于 2019-11-29 11:56:38
BalusC

Do not use ExternalContext#dispatch(), ever. This method has no single sensible use case in a decent JSF web application. It only corrupts the JSF life cycle because it creates another FacesContext within the current request. You should use JSF's own NavigationHandler or use ExternalContext#redirect().

When you're already on JSF 2.2, use <f:viewAction action="#{bean.init}"> which supports a navigation case outcome (like <h:commandButton action>):

public String init() {
    // ...
    return "someViewId";
}

Or when you're still on JSF 2.0/2.1, and can thus only use <f:event type="preRenderView">, and given that you're using OmniFaces use its Faces#navigate() or Faces#redirect():

public void init() {
    // ...
    Faces.navigate("someViewId");
}

In case you aren't using OmniFaces, here's how it's implemented:

public void init() {
    // ...
    FacesContext context = FacesContext.getCurrentInstance();
    context.getApplication().getNavigationHandler().handleNavigation(context, null, "someViewId");
}

Note that this all may still fail when using @PostConstruct instead of f:viewAction or preRenderView. See also a.o. Redirect in @PostConstruct causes IllegalStateException.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!