Search code examples
jsfrefreshcommandbutton

Calling Managed bean function without changing page


In JSF 2.2 whenever I have a line like in a xhtml page: <h:commandButton value="Click Me!" action="whatever" />. Clicking this button causes the browser to "move forward" so that I can click the back button and remain on that xhtml page. That means when I click the commandButton ten times I can go back ten times by pressing the back button of the browser. What can I do to make the button not changing the page? I want to be able to click on such a button and in some cases change the page and in some stay on the current one without making a step in history of the browser.


Solution

  • Using AJAX would be a possible solution for your problem.

    If you use a command button inside a form element, a click sends the form data with a post request to the server.

    <h:form>
        <h:inputText id="inputId" value ="#{testController.message}"></h:inputText>
        <h:commandButton value="submit" action="#{testController.reverse}" />
    </h:form>
    

    If you use the AJAX element inside a command button, just the data specified by the execute attribute will be send to the server. The response contains only a part of the html file specified by the render attribute. This part will be inserted in the existing html file. By using AJAX not the whole page is refreshed therefore it doesn’t affect the browser history.

    <h:form>
        <h:inputText id="inputId" value ="#{testController.message}"></h:inputText>
        <h:commandButton value="inputId" action="#{testController.reverse}" >
            <f:ajax execute="inputId" render="outputId" />
        </h:commandButton>
    </h:form>
    
    <h:outputText id="outputId" value="#{testController.output}"/>