如何在preRenderView侦听器方法中执行导航

use*_*895 6 navigation listener jsf-2 prerenderview

我从什么可以<f:metadata>,<f:viewParam>和<f:viewAction>开始?

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

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

它调用以下方法:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

和以下导航规则:

<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>
Run Code Online (Sandbox Code Playgroud)

但是,它不执行导航.它使用命令按钮时,如下所示:

<p:commandButton ... action="#{loginBean.performWeakLogin()}"  /> 
Run Code Online (Sandbox Code Playgroud)

Bal*_*usC 10

基于方法的返回值的导航仅由实现ActionSource2接口的组件执行,并提供用于获取该属性的属性MethodExpression,例如组件的action属性UICommand,其在应用请求值阶段期间排队并在调用应用阶段期间调用.

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

public void performWeakLogin() {
    // ...

    FacesContext fc = FacesContext.getCurrentInstance();
    fc.getApplication().getNavigationHandler().handleNavigation(fc, null, "mainPortal");
}
Run Code Online (Sandbox Code Playgroud)

或者,您也可以发送给定URL的重定向,这对于您不希望在内部导航但在外部导航的情况更有用:

public void performWeakLogin() throws IOException {
    // ...

    ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
    ec.redirect(ec.getRequestContextPath() + "/stdPortal/stdPages/mainPortal.xhtml");
}
Run Code Online (Sandbox Code Playgroud)

具体问题无关,servlet过滤器是执行基于请求的授权/认证工作的更好地方.

也可以看看: