繁体   English   中英

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

[英]How to use ExternalContext.redirect() in JSF2.0?

考虑一个页面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>
...

按钮操作绑定到控制器方法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"   
   }
}

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

如果myCondition为true,我想将用户重定向到http://www.myTarget.com/thePage.html 如果myCondition为false,他将不得不留在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.

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

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

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

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

理论上,在重定向发生时,这应该不会发生。 尝试将return null添加到try块。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM