Explicit url redirect in JSF 2.0

2019-05-24 06:50发布

问题:

I have the following two pages below.

hello.xhtml, rendered by .../hello.jsf url.

<h:form>
  <h:commandButton id="submit" value="Submit" action="response"/>
</h:form>

response.xhtml, rendered by .../response.jsf url.

<h:form>
  <h:commandButton id="back" value="Back" action="hello"/>
</h:form>

When Submit button is clicked, the hello page is redirected to the response page but the url remains the same, i.e., the url is still .../hello.jsf.

I'd like the url to be .../response.jsf after the Submit button is clicked. Any help, please?

Many thanks!

回答1:

If you are actually not using old fashioned JSF navigation cases as implied by kolossus, but are instead using new JSF2 implicit navigation feature, then just add faces-redirect=true query string parameter to the outcome.

<h:form>
  <h:commandButton id="submit" value="Submit" action="response?faces-redirect=true" />
</h:form>

However, if you don't need to invoke any bean action at all, and intend to use plain page-to-page navigation, then it makes no sense to perform a POST request for this. Just use the <h:button> then.

<h:button id="submit" value="Submit" outcome="response" />

See also:

  • Difference between h:button and h:commandButton
  • When should I use h:outputLink instead of h:commandLink?


回答2:

Add the redirect attribute to your faces_config.xml file like so:

 <navigation-rule>
    <from-view-id>/hello.xhtml</from-view-id>
    <navigation-case>
        <from-outcome>response</from-outcome>
        <to-view-id>/response.xhtml</to-view-id>
       <!--the redirect element -->
        <redirect/>
    </navigation-case>
</navigation-rule>

EDIT: I got the impression that you're using a faces-config.xml from your navigation outcome styling. I have confirmed personally that what you're doing is also permissible for the new JSF 2 style navigation. See BalusC's answer for using the redirect url parameter in a JSF2-style navigation handling



标签: url jsf redirect