JSF重定向到其他页面

yas*_*ash 5 jsf redirect submit

我有三个XHTML页面;

  1. 的index.xhtml
  2. page_1.xhtml
  3. page_2.xhtml

index.xhtml页面中,我有一个commandButton发送给用户的page_1.xhtml.所有这些都在导航规则中完成faces-config.xml.

如何将用户重定向到page_2.xhtmlindex.xhtml使用另一个commandButton假设两者commandButtons的行为都与后备Java类?

Bal*_*usC 20

只需将按钮绑定到不同的操作方法,每个操作方法返回不同的结果.

<h:commandButton value="Go to page 1" action="#{bean.goToPage1}" />
<h:commandButton value="Go to page 2" action="#{bean.goToPage2}" />
Run Code Online (Sandbox Code Playgroud)

public String goToPage1() {
    // ...
    return "page_1";
}

public String goToPage2() {
    // ...
    return "page_2";
}
Run Code Online (Sandbox Code Playgroud)

导航案例不是必需的.JSF 2.0支持隐式导航.导航结果可以是所需目标视图的路径/文件名.结果中的文件扩展名是可选的.

如果您不一定需要在导航上执行任何业务操作,或者您可以在目标页面的辅助bean的(post)构造函数中执行此操作,那么您也可以直接将结果值放入action.

<h:commandButton value="Go to page 1" action="page_1" />
<h:commandButton value="Go to page 2" action="page_2" />
Run Code Online (Sandbox Code Playgroud)

<h:commandButton>但是,A 不会执行重定向,而是执行重定向.最终用户将不会在浏览器地址栏中看到更改的URL.目标页面不可收藏.如果可以,我建议<h:button>改用.

<h:button value="Go to page 1" outcome="page_1" />
<h:button value="Go to page 2" outcome="page_2" />
Run Code Online (Sandbox Code Playgroud)

或者,如果您确实需要调用业务操作,但希望执行实际重定向,则将faces-redirect=true查询字符串附加到结果值.

public String goToPage1() {
    // ...
    return "page_1?faces-redirect=true";
}

public String goToPage2() {
    // ...
    return "page_2?faces-redirect=true";
}
Run Code Online (Sandbox Code Playgroud)

也可以看看:


小智 5

您也可以在代码的任何部分中执行此操作,以重定向到“example.xhtml”

ExternalContext ec = FacesContext.getCurrentInstance()
        .getExternalContext();
try {
    ec.redirect(ec.getRequestContextPath()
            + "/faces/jsf/example.xhtml");
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)