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

18,582

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.

Share:
18,582
Jan
Author by

Jan

Updated on June 27, 2022

Comments

  • Jan
    Jan almost 2 years

    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.