开发者

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

Consider a page 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>
...

The button action is bound to a controller method 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"   
   }
}

My first question is: Does the above makes sense? Is this a correct way of using redirect()?

I want to redirect the user to http://www.myTarget.com/thePage.html in case myCondition is true. If myCondition is false, he will have to stay on myPage.xhtml.

If so, I would like to understand better what happens... When using Live HTTP Headers in Firefox, I observe that when clicking the button

  1. a POST to webapp/myPage.xhtml occurs
  2. the server replies with 302 Moved Temporarily - Location: www.myTarget.com/thePage.html
  3. the browser GET's www.myTarget.com/thePage.html

So far, Is this the expected behaviour?

What I find annoying now is that webapp/myPage.xhtml is called. More specifically, that the preRenderView-event is called here again. (I have a bit of code in the preRenderView-listener that should be executed only once.)

Does the above make sense? Does anybody see a way to improve this?

Thank you! J.


So far, Is this the expected behaviour?

A redirect basically instructs the client to fire a new HTTP request on the URL as specified in the Location response header. So yes, the behaviour as you're seeing is correct.

However, your URL is wrong. It's relative to the current request URL. So if the current URL is for example http://example.com/context/page.jsf, then this redirect will basically point to http://example.com/context/www.myTarget.com/thePage.html which is obviously wrong. When the new URL concerns a different domain, you should redirect to an absolute URL. In other words, prefix it with the http:// scheme.

What I find annoying now is that webapp/myPage.xhtml is called.

This should in theory not happen when the redirect has taken place. Try adding return null to the try block.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜