Search code examples
jsf-2

Update URL parameters after method call


This should be simple, but I am looking at other questions and I am not able to find the right answer for my issue.

I have a JSF page that calls a method myController.load():

<f:metadata>
     <f:viewParam name="id" value="#{myController.id}" required="false"/>
     <f:viewAction action="#{myController.load()}" />

This method will generate an id that is placed in myController.id if originally the page was not called with such parameter. My question is how can I make the URL at the navigation bar reflect this change, i.e. insert this new parameter in the URL. Basically:

--> Browse to myPage.xhtml

--> call to myController.load() which sets myController.id = 1

--> Reflect in URL myPage.xhtml?id=1. Ideally without re-loading the page


Solution

  • You will want to do some reading about PRG (Post/Redirect/Get). Here is a good start.

    https://mobiarch.wordpress.com/2012/08/09/doing-post-redirect-get-pattern-in-jsf-2/

    You'll want your original JSF link to call an ActionListener that will create a scoped reference to myController and set the id attribute to 1 there... then you can use PRG to redirect to your page. PRG will use the value of your bean to build the new URL correctly as you want.

    This ActionListener method is very simple just to help illustrate...

    // my ActionListener method
    public String goToMyPage() {
        myController.setId(1); // assuming myController is declared in scope.
    
        return "myPage?faces-redirect=true&includeViewParams=true";
    }
    

    Hope this helps get you started.