如何在preenderview监听器方法中进行导航



我从What can 和& lt; f: viewAction>被用于?

我有一个预呈现视图事件监听器:

<f:metadata>
    <f:event type="preRenderView" listener="#{loginBean.performWeakLogin()}" />
</f:metadata>

调用以下方法:

public String performWeakLogin() {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    String parameter_value = (String) facesContext.getExternalContext().getRequestParameterMap().get("txtName");
    if (parameter_value != null && parameter_value.equalsIgnoreCase("pippo")) {
        try {
            return "mainPortal";
        } catch (IOException ex) {
            return null;
        }
    } else {
        return null;
    }
}

和以下导航规则:

<navigation-rule>
    <from-view-id>/stdPortal/index.xhtml</from-view-id>
    <navigation-case>
        <from-outcome>mainPortal</from-outcome>
        <to-view-id>/stdPortal/stdPages/mainPortal.xhtml</to-view-id>
        <redirect/>
    </navigation-case>
</navigation-rule>

但是,它不执行导航。当我使用命令按钮时,它可以工作,如下所示:

<p:commandButton ... action="#{loginBean.performWeakLogin()}"  /> 

基于方法返回值的导航只能由实现ActionSource2接口并为其提供一个带有MethodExpression的属性的组件进行,例如UICommand组件的action属性,在Apply Request Values阶段排队,在Invoke Application阶段调用。

<f:event listener>仅仅是一个组件系统事件监听器方法,而不是一个操作方法。您需要手动执行如下导航:

public void performWeakLogin() {
    // ...
    FacesContext fc = FacesContext.getCurrentInstance();
    fc.getApplication().getNavigationHandler().handleNavigation(fc, null, "mainPortal");
}

或者,你也可以在给定的URL上发送一个重定向,这对于你不想在内部导航,而是想在外部导航的情况更有用:

public void performWeakLogin() throws IOException {
    // ...
    ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
    ec.redirect(ec.getRequestContextPath() + "/stdPortal/stdPages/mainPortal.xhtml");
}

与具体问题无关,servlet过滤器是执行基于请求的授权/身份验证工作的更好场所。

参见:

    是否有任何简单的方法来预处理和重定向GET请求?

我使用JBoss 7和JSF 2.1。BalusC的解决方案是重定向到JBoss默认错误页面,尽管我已经在web.xml中设置了默认错误页面。

<error-page>
    <error-code>404</error-code>
    <location>/myapp/404.xhtml</location>
</error-page>

要重定向到我自己的错误页面,我使用响应发送错误:

FacesContext facesContext = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse)facesContext.getExternalContext().getResponse();
try {
    response.sendError(404);
} catch (IOException ioe) {
    ioe.printStackTrace();
}
facesContext.responseComplete();

最新更新