如何使用导航规则进行重定向

tim*_*nYE 8 navigation jsf redirect jsf-2

JSF中的Bean重定向可以通过以下方式完成

externalContext.redirect("foo.xhtml");
Run Code Online (Sandbox Code Playgroud)

但我想使用规则,在<navigation-rule/>(faces-config.xml)中为<from-outcome/>&&传递命令行参数设置.

externalContext.redirect("from-outcome?param=bar");
Run Code Online (Sandbox Code Playgroud)

不管用.怎么做?

Bal*_*usC 14

ExternalContext#redirect() 接受一个URL,而不是一个导航的结果.

您需要从声明返回的操作方法返回导航结果String.

public String submit() {
    // ...

    return "from-outcome";
}
Run Code Online (Sandbox Code Playgroud)

您可以配置导航案例以通过添加发送重定向<redirect>.

<navigation-rule>
    <navigation-case>
        <from-outcome>from-outcome</from-outcome>
        <to-view-id>/foo.xhtml</to-view-id>
        <redirect>
            <view-param>
                <name>param</name>
                <value>bar</value>
            </view-param>
        </redirect>
    </navigation-case>
</navigation-rule>
Run Code Online (Sandbox Code Playgroud)

请注意,您也可以使用JSF隐式导航而无需此XML混乱:

public String submit() {
    // ...

    return "/foo.xhtml?faces-redirect=true&param=bar";
}
Run Code Online (Sandbox Code Playgroud)

如果你在一个无法返回字符串结果的事件或ajax监听器方法中,那么你总是可以抓住它NavigationHandler#handleNavigation()来执行所需的导航.

public void someEventListener(SomeEvent event) { // AjaxBehaviorEvent or ComponentSystemEvent or even just argumentless.
    // ...

    FacesContext context = FacesContext.getCurrentInstance();
    NavigationHandler navigationHandler = context.getApplication().getNavigationHandler();
    navigationHandler.handleNavigation(context, null, "from-outcome");
}
Run Code Online (Sandbox Code Playgroud)

非导航案件的等价物正在使用ExternalContext#redirect().