如何在JSF2.0中使用ExternalContext.redirect()?

Jan*_*Jan 3 java jsf jsf-2

考虑一个页面webapp/myPage.xhtml:

...
<h:form id="myForm">
    ...
    <h:selectOneMenu id="..." required="true" value="#{myController.aValue}">
       <f:selectItems value="#{...}" var="..." itemValue="#{...}" itemLabel="#{...}"/>
    </h:selectOneMenu>
    ...
    <h:commandButton value="Go for it!" action="#{myController.goForIt(...)}"/>
    ...
</h:form>
...
Run Code Online (Sandbox Code Playgroud)

按钮操作绑定到控制器方法MyController.goForIt():

@ManagedBean(name = "myController")
@RequestScoped
public class MyController {
   public String goForIt(...){
      if (myCondition){
         try {
            FacesContext.getCurrentInstance().getExternalContext()
                        .redirect("http://www.myTarget.com/thePage.html");
         } catch (IOException e) {
           ...
         }
      }
      return "myPage.xhtml"   
   }
}
Run Code Online (Sandbox Code Playgroud)

我的第一个问题是:上述内容是否有意义?这是使用redirect()的正确方法吗?

我想重定向用户http://www.myTarget.com/thePage.html,以防万一myCondition.如果myCondition是假的,他将不得不留下来myPage.xhtml.

如果是这样,我想更好地了解会发生什么...... 在Firefox中使用Live HTTP Headers时,我会发现单击按钮时

  1. 发生对webapp/myPage.xhtml的POST
  2. 服务器回复302暂时移动 - 位置:www.myTarget.com/thePage.html
  3. 浏览器GET的www.myTarget.com/thePage.html

到目前为止,这是预期的行为吗?

我现在觉得烦人的是调用webapp/myPage.xhtml.更具体地说,再次调用preRenderView -event.(我在preRenderView-listener中有一些代码应该只执行一次.)

以上是否有意义?有没有人看到改善这种情况的方法?

谢谢!J.

Bal*_*usC 8

到目前为止,这是预期的行为吗?

重定向基本上指示客户端在响应头中指定的URL上触发新的 HTTP请求Location.所以是的,你所看到的行为是正确的.

但是,您的网址有误.它与当前请求URL相关.因此,如果当前的URL是例如http://example.com/context/page.jsf,那么,此重定向将基本指向http://example.com/context/www.myTarget.com/thePage.html这是显然错了.当新URL涉及不同的域时,您应该重定向到绝对 URL.换句话说,使用http://方案作为前缀.

我现在觉得烦人的是调用webapp/myPage.xhtml.

理论上,在重定向发生时,这应该不会发生.尝试添加return nulltry块.