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

时间:2013-08-29 13:37:09

标签: jsf redirect jsf-2 navigation

JSF中的Bean重定向可以通过

完成
externalContext.redirect("foo.xhtml");

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

externalContext.redirect("from-outcome?param=bar");

不工作。怎么做?

1 个答案:

答案 0 :(得分:13)

ExternalContext#redirect() takes an URL,而不是导航结果。

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

public String submit() {
    // ...

    return "from-outcome";
}

您可以通过添加<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>

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

public String submit() {
    // ...

    return "/foo.xhtml?faces-redirect=true&param=bar";
}

如果你在一个无法返回字符串结果的事件或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");
}

非导航用例相当于使用ExternalContext#redirect()