简体   繁体   中英

show working image while executing h:commandlink action

To add an article, I have <h:commandlink> that executes an action which redirect to a success or error page depending on action results. The action takes a while to finish its execution, approximately 4 seconds. Could you tell me how to display a loading image when action begins to execute and hide it when action terminates?

You will need to use ajax for the task at hand. Using plain vanilla JSF and some javascript, this would be the solution:

<h:form>
    <h:commandLink value="Submit" action="#{yourManagedBean.desiredAction}">
        <f:ajax onevent="showProgress" />
    </h:commandLink>
    <!-- other components... -->

    <!-- External div which wraps the loading gif -->
    <div id="divProgress" style="display: none; height: 60px; overflow: hidden;">
        <div style="display: table-cell; vertical-align: text-top;">
            Working...
            <!-- Locate your gif wherever you stored -->
            <h:graphicImage url="resources/images/loading.gif" height="49" width="49" />
        </div>
    </div>

    <script type="text/javascript">
        function showProgress(data) {
            var ajaxStatus = data.status;
            switch (ajaxStatus) {
                case "begin":
                    //This is called right before ajax request is been sent.
                    //Showing the div where the "loading" gif is located
                    document.getElementById("divProgress").style.display = 'table';
                    break;

                case "success":
                    //This is called when ajax response is successfully processed.
                    //In your case, you will need to redirect to your success page
                    var url = window.location.protocol + "//"
                        + window.location.host + "/"
                        + (window.location.port ? ":"+ window.location.port: "");
                    window.location.href = url + "#{request.contextPath}/" + "#{yourManagedBean.resultUrl}";
                    break;
            }
        }
    </script>
</h:form>

And in your managed bean:

@ManagedBean
@ViewScoped
public class YourManagedBean {
    private String resultUrl;
    //getters and setters...
    public void desiredAction() {
        //do the processing...
        if (...) {
            resultUrl = "success.xhtml";
        } else {
            resultUrl = "error.xhtml";
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM